C++ Class Inheritance with added members

Introduction

The derived class inherits public and protected members of a base class and can introduce its own members.

A simple example:


class MyBaseClass 
{ 
public: /*from  w  ww .  ja  va 2  s. c o  m*/
    char c; 
    int x; 
}; 

class MyDerivedClass : public MyBaseClass 
{ 
public: 
    double d; 
}; 

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

Here we inherited everything from the MyBaseClass class and introduced a new member field in MyDerivedClass called d.

So, with MyDerivedClass, we are extending the capability of MyBaseClass.

The field d only exists in MyDerivedClass and is accessible to derived class and its objects.

It is not accessible to MyBaseClass class as it does not exist there.




PreviousNext

Related