Welcome, this is Dr. Cu.

Lonely in the Dessert.

About Inheritance in C++

As a general rule, a derived class / subclass can freely access all of base class / superclass’s public and protected members, but not the private ones. In C++, you can specifically indicate the styles how derived classes inheritates the members, in terms of three different kinds of inheritance.

Grammar of inheritances
class DerivedClass : public BaseClass{};
class DerivedClass : protected BaseClass{};
class DerivedClass : private BaseClass{};
  • Public Inheritance Inheritated members (public, protected) of base classes remain public and protected.
  • Protected Inheritance Inheritated members (public, protected) of base classes are both changed to protected.
  • Private Inheritance Inheritated members (public, protected) of base classes are both changed to private.

Public Inheritance is used most often. Private Inheritance is also used to implement one class in terms of another class. However, protected inheritance is rarely used.

If you are familiar with Java, you should benefit a lot from the Interface concept which facilitates software engineerings. In C++, abstract class without data members serve more or less (not exactly the same) similar functions.

Generally speaking, abstract base class contains at least one virtual method htat has no implementations (pure virtual functions). Implicitly, those derived classes that don’t implement all of the pure virtual methods are also abstract base classes and can’t instantiate any instances.

Constructors cannot be virtual, and therefore can’t be pure, so the abstract class can provide the constructor implementations. For the destructors, they can’t be pure, because they will be invoked by derived classes even only empty bodies are provided. In addition, virtual destructors are recommended. If you have any doubts on this statement, please consider this example.

A function which destroys an object from heap memory
void release()
    BaseClass* p = new DerivedClass();
    delete p;

To summerize, an abstract class is:

  • Contains at least one pure virtual method.
  • Defines a niminum interface for its descendants.
  • No instances.
  • Provides no implementations except for the destructors and accessors for private data members.
  • Must implement any virtual methods that are not pure. They serve as default implementations if derived classes choose not to supply their own.