Moving templates in front of C++ templates remaining slides on inheritance z Like “blueprints” for the compiler to use in For the sake of assignment 5 – creating class and function definitions covering chapter 12 before finishing chapter 11 – Repeat – the compiler writes the code for you z Involve one or more parameterized types – e.g., function template to compare object sizes template
Function templates More function templates
z Template definition must be in header file z Alternative to function overloading – Compiler must know how to define function – But code for concrete types created only as needed z So template cannot be in separate .cpp file z And the programmer does not have to write it! – Compiler deduces parameter types if not specified z Can specialize for particular types int x = sizeComp(‘a’, 7); // now the compiler will use – Tells the compiler to use specialized version instead the template to create sizeComp(char, int) of creating a new definition // specify x = sizeComp
Class templates Implementing class templates z Alternative to inheritance – and more flexible z All but specializations must be in header file – No cosmic superclass in C++ (like ) java.lang.Object – Compiler can’t write the class without the blueprint z Objects are always a particular type z Note: the separate compilation model using the export – e.g., List
1 Back to inheritance topics Inheriting functions virtual functions z Function hiding – if function defined in derived class z Polymorphism is not automatic in C++ with same name as function(s) in base class –Hides all non-virtual base class functions with same name – Function must be declared virtual in base class – But can do using Base::name to unhide z Otherwise derived class will hide it, not override it z Virtual functions stay virtual for all descendants z Manager functions are never inherited – But still often must access – e.g., always need base’s ctor – See …/demo08/loans/ example z Can use Base(arg list) in derived class’s initializer list z Note: dtors must be virtual to allow derivation z In operator= and others – use scope resolution Base::operator=(…) z Abstract base classes – any class with a “pure z Upcasts – base pointer/reference for derived instance OK virtual” function – cannot be instantiated per se – Never upcast with arrays – different sizes ruin pointer arithmetic – e.g., virtual void func() = 0; // pure virtual – Called “object slicing” if derived instance copied to base instance z Derived classes must implement or they are abstract too – All instances are actually derived class instances
2