











Inheritance in C++


Inheritance in C++
Inheritance in C++ is basically the ability for a class to be able to derive its properties from a different class. It is the most important feature of object oriented programming and allows –
- High code re-use
- Lesser time to code
- Easier to maintain application and edit codes
- Re-use pre-defined properties and data
Benefits of Inheritance
- This helps in reduce cost for projects
- Saves time in coding
- Decreases complexity of the program
- Increases reliability


Different Modes of Inheritance in C++
There are three different ways in which we can define relationship between base and derived class while defining inheritance –
- Public mode:
- Public members of base class become public in derived class
- Protected members of base class become Protected in derived class
- Private members are inaccessible in derived class
- Protected mode:
- Public members of base class become protected in derived class
- Protected members of base class become Protected in derived class
- Private members are inaccessible in derived class
- Private mode:
- Public members of base class become private in derived class
- Protected members of base class become private in derived class
- Private members are inaccessible in derived class


Syntax for Inheriting Declaration –
class NameOfDerivedClass : (Visibility mode) NameOfBaseClass{
// Data Members and functions
}
In terms of Parent and Child nomenclature –
class NameOfChildClass : (Visibility mode) NameOfParentClass{
// Data Members and functions
}
Example
The following example explains really well how inheritance really works and ways different members are accessible or not accessible –
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x stays public
// y stays protected
// z is not accessible from B
};
class C : protected A {
// x becomes protected
// y stays protected
// z is not accessible from C
};
// 'private' is default for classes
class D : private A {
// x becomes private
// y becomes private
// z is not accessible from D
};
Login/Signup to comment