Inheritance in OOPs C++

In C++, inheritance is a method in which one object acquires all the properties and behaviors of it’s parent object automatically. In this approach, we can reuse or modify the attributes which are defined in the other class.

Inheritance is one among the key features/concepts of Object oriented programming. It allows us to create a new class i.e. the derived class, from an existing base class.

Derived Class: The class which inherits properties from another class is called Sub class or Derived Class. 
Base Class:The class whose properties are inherited by a sub class is called Base Class or Super class. 

Advantage of Inheritance

  • Code re-usability: We can reuse the members of the parent class. So, we need not define the member again and less code is required in the class.
  • Avoids duplication of data: Class members need not be defined repeatedly, hence the repeatition of data is avoided.

Basic Example:

class Animal {
    // eat() function
    // sleep() function
};

class Dog : public Animal {
    // bark() function
};

In this, the class ‘Dog’ is derived from the class ‘Animal’. Since ‘Dog’ is derived from ‘Animal’ ,the members of  ‘Animal’ are accessible to ‘Dog’. Here, we use the keyword ‘public’.

Dog class inherits from the Animal class

Output:

class Dog : public Animal {...};

We wil study about the differences between private, public and protected modes using private, public in the next part of this tutorial.

Modes of Inheritance

  1. Public mode: to derive a sub class from a public base class. The public members of the base class becomes public in the derived class. The protected members of the base class will become protected in derived class.
  2. Protected mode: to derive a sub class from a Protected base class. Then both public and protected members of the base class will become protected in derived class.
  3. Private mode: to derive a sub class from a Private base class. In the derived class, the public and protected members of the base class, both become Private. 

Example:

class A {
public:
    int a;
protected:
    int b;
private:
    int c;
};
class B : public A {
    // a is public
    // b is protected
    // c is not accessible from B
};
class C : protected A {
    // a is protected
    // b is protected
    // c is not accessible from C
};
class D : private A     
{    // a is private
      // b is private
     // c is cannot be accessed from D
};

The base class private members cannot be directly accessed by the derived class. However,the protected members can be directly accessed. The derived class also inherits a full parent object.

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!๐Ÿ‘‹
Can we help you?