C++

C++ Inheritance (1)

1.

Bass class needs virtual destructor. The type of reference or pointer of a class will determine function to call where there is no virtual used in base class. If virtual is used in base class, the type of class that is pointed by pointer or reference determines which function to call. Better to use virtual in derived class to point out this function is virtual function derived from base class. virtual can only be used in declaration.

//dosth() is non-virtual

BaseClass& base = BaseClass() ;

BaseClass& derive = DerivedClass();

base.dosth();      //use BaseClass :: dosth()

derived.dosth(); //use BaseClass :: dosth()

//dosth() is virtual

BaseClass& base = BaseClass() ;

BaseClass& derive = DerivedClass();

base.dosth();      //use BaseClass :: dosth()

derived.dosth(); //use DerivedClass :: dosth()

 

2.

Always setup explicit default constructor to make sure member has proper initial value.

If child class has no dynamic memory allocation, it does not need explicit copy constructor, destructor and assignment operator.

In this case, base class can have dynamic memory allocation or not.

Leave a comment