C++ - Inheritance


Advertisements

Previous Page Next Page

Inheritance enables a class to inherit the properties and methods from another class. The class which is being inherited is called base class or parent class. The class which inherits from another class is called derived class or child class. Inheritance provides re usability of a code and adds more features to a class without modifying it.

Create derived Class

To create a derived class, it is must to specify access specifier and the base class when it is created. Please see the syntax below. A derived class inherits all public and protected members of base class, and the access specifier defines how these class members of the base class will be inherited in the inherited class.

Syntax


//defining a class
class base_class
  {
    class memebers;
  };

//defining a derived class
class derived_class: access_specifier
  {
    code statements;
  };

Example:

In the below example, a base class called Polygon is created which has two data members called length and breadth. Rectangle, a derived class of Polygon is also created using public access specifier. The derived class Rectangle inherits all public and protected members of base class Polygon.

#include <iostream>
using namespace std;
 
class Polygon
 {
   public:
     int length = 5;
     int breadth = 10;
 };

class Rectangle: public Polygon
{};

int main (){
    Rectangle MyRectangle;
    cout<<MyRectangle.length<<"\n";
    cout<<MyRectangle.breadth<<"\n";
}

Output

5
10

Access Specifier of Inherited members

Class function also known as class method can be defined in two ways.

  • Inside class definition
  • Outside class definition

Example: Class function defined inside class

In the below example, a class function called area is defined inside the class Circle. A class function can be accessed in the same way as other class members, using dot (.) syntax.

#include <iostream>
using namespace std;
 
class Circle
 {
   public:
     int radius = 10;
     void area()
     {
      float x;
      x = 22/7.0*radius*radius;
      cout<<x;
     }
 };

int main (){
    Circle MyCircle;
    MyCircle.area(); 
    return 0;
}

Output

314.3

Example: Class function defined outside class

To define a class function outside the class, scope operator (::) is used. It starts with class name followed by scope operator and function name. Along with this, the function must be declared inside the class as shown in the below example.

#include <iostream>
using namespace std;
 
class Circle
 {
   public:
     int radius = 10;
     void area();
 };

void Circle::area()
 {
    float x;
    x = 22/7.0*radius*radius;
    cout<<x;
 }

int main (){
    Circle MyCircle;
    MyCircle.area(); 
    return 0;
}

Output

314.3

Previous Page Next Page