Inheritance in C++
- The mechanism of deriving a class from another class is known as Inheritance.
- Inheritance is the most importance concept of object oriented programming.
- It allows us to define a class in terms of another class, which helps to create and maintain an application.
- The main advantage of Inheritance is, it provides an opportunity to reuse the code functionality and fast implementation time.
- The members of the class can be Public, Private or Protected.
class DerivedClass : AccessSpecifier BaseClass
- The default access specifier is Private.
- Inheritance helps user to create a new class (derived class) from a existing class (base class).
- Derived class inherits all the features from a Base class including additional feature of its own.
|From own class||Yes||Yes||Yes|
|From derived class||No||Yes||Yes|
|Outside derived class||No||Yes||No|
Example: Program demonstrating implementation of Inheritance
using namespace std;
float width, height;
void set_data (float w, float h)
width = w;
height = h;
class Rectangle: public Shape
float area ()
return (width * height);
class Triangle: public Shape
float area ()
return (width * height / 2);
int main ()
cout << "Area of Rectangle : "<<r.area() << endl;
cout << "Area of Triangle : "<<t.area() << endl;
Area of Rectangle: 16
Area of Triangle: 10.5
In the above example, class Shape
is a base class
and classes Rectangle
are the derived class.
The derived class appears with the declaration of class followed by a colon(:), access specifier public and the name of the base class from which it is derived.
are derived from Shape class,
all the data members and member functions of the base class Shape
can be accessible from derived class.