Notes on inheritance
.
public inheritance models an IS-A relationship (private inheritance models a HAS-A relationahip, and is less useful in the context of this course)
protected base-class members are visible in the derived class
(However, a derived class method cannot access the protected member of an object of the base class type)
- The default constructor in the derived class is
derived( ) : base( ) {}
- If you define a constructor
derived(...){...}
then the compiler will call the default (zero-argument) constructor prior to executing this constructor. To prevent this, you must explicitly call the appropriate base constructor in the initializer list of the derived class constructor:
derived(... ) : base(...) {...}
- All public methods are inherited into the derived class, but may be overridden, or partially overridden, in the derived class
- Polymorphism
is the ability of a reference or a pointer variable to refer to (or point to) different kinds of objects. In C++, a variable declared as a reference to (or a pointer to) a base class can reference (or point to) either a base class object, or a derived class object.
- C++’s default is static binding of methods; to force dynamic binding, a method should be declared as being virtual in the base class:
virtual returnType fnName(..) {...}
Virtualness is inherited – i.e., a method declared virtual in the base class is also virtual in the derived classes.
Only functions whose meanings are invariant over the netire inheritance hierarchy should not be declared virtual.
Default constructors, copy constructors, assignment operator, and destructor:
If any of these is not defined in the derived class, it is default implemented by a call to the function for the base class, followed by calls to the function for any additional data members. E.g., in the code handed out in class
const compStudent & operator=(const compStudent & rhs);
if not defined in class compStudent, is implemented by a call to operator= for the base class (student), followed by the copying of the string "comp"
- If any of these functions are declared private in the base class, they’re disabled in the derived class (because the base call cannot be made in the derived class)
- Declaring a constructor virtual is meaningless (and therefore forbidden)
- A destructor should always be declared virtual
- An abstract method (also known as a pure virtual function) is declared in the base class, but defined in the derived class
[Specifies (in the base class) the methods that all derived classes must implement, but leaves it to the derived classes to determine how.]
virtual
returnType fnName (argList) = 0;
- A class with at least one abstract method is called an abstract class
- Abstract classes cannot be instantiated!
- Friends
– friendship is not inherited