Templates
Transcript: Templates The key to generic programs a simple code! Output? Answer Namespaces Namespace is a feature added in C++ and not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc) inside it. Multiple namespace blocks with the same name are allowed. Templates Templates Templates are powerful features of C++ which allows you to write generic programs. In simple terms, you can create a single function or a class to work with different data types using templates. Advantages: Readability Flexibility Re-usability Function Template FUnction Templates A single function template can work with different data types at once but, a single normal function can only work with one set of data types. Normally, if you need to perform identical operations on two or more types of data, you use function overloading. However, a better approach would be to use function templates because you can perform the same task writing less and maintainable code. Example Sometimes, you need a class implementation that is same for all classes, only the data types used are different. Normally, you would need to create a different class for each data type OR create different member variables and functions within a single class. This will unnecessarily bloat your code base and will be hard to maintain, as a change is one class/function should be performed on all classes/functions. Class Template Class Templates Example virtual functions virtual functions Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. They are mainly used to achieve Run-time polymorphism. The prototype of virtual functions should be same in base as well as derived class. They are always defined in base class and overridden in derived class. It is not mandatory for derived class to override Example Pass by reference Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. Does not copy the arguments. The formal parameter is an alias for the argument. References cannot be NULL.