C++ Class Inheritance with three levels

Introduction

A derived class itself can be a base class.

Example:

class MyBaseClass 
{ 
public: //from w w  w  . ja v  a2s  . c om
    char c; 
    int x; 
}; 
class MyDerivedClass : public MyBaseClass 
{ 
public: 
    double d; 
}; 

class MySecondDerivedClass : public MyDerivedClass 
{ 
public: 
    bool b; 
}; 

int main() 
{ 
    MySecondDerivedClass o; 
    o.c = 'a'; 
    o.x = 123; 
    o.d = 456.789; 
    o.b = true; 
} 

Now our class has everything MyDerivedClass has, which includes everything MyBaseClass has, plus an additional bool field.

It is said the inheritance produces a particular hierarchy of classes.

This approach is widely used when we want to extend the functionality of our classes.

The derived class is compatible with a base class.

A pointer to a derived class is compatible with a pointer to a base class.




PreviousNext

Related