Comparing Java and C++ Inheritance

1) Naming the base class

Java says ‘extends’, c++ uses a colon.

class Java extends Baseclass

{}

 

class Cplusplus : Baseclass

{};

 

 

2) Multiple Inheritance

Java says each class can have at most one base class

C++ says each class can have any number of base classes.  If those base classes have items of the same name, then you better be clear which one you mean when you use this shared name.

 

3) Interfaces

Java has interfaces.  This helps them overcome the limitations of not having multiple inheritance.

C++ doesn’t.  It uses multiple base classes and “abstract base classes” instead.

 

4) Calling the constructor of the base class

In Java, you say super.

In C++, you use a colon.

public foo(int arg)
{

    super(foo);
    // Other stuff
}

foo(int arg) : base(arg)
{

    // Other stuff
}

5) Virtual Functions

In Java, every function is virtual.   You have no other choice. 

In C++, things are only virtual if you say so.  Remember, constructors cannot be virtual by c++ law.

6) Constructor Order

In both languages, the base class’s constructor is called, then the derived class.

7) Destructors

In Java, there is no such thing.

In c++, they exist.  They are called for the derived class, then the base class.  This is the opposite order of the constructors.