Single Inheritence In C++


A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:

class derived_class_name :: visibility-mode base_class_name  
{  
    // body of the derived class.  
}  
 
 
Where,
derived_class_name: It is the name of the derived class.
visibility mode: The visibility mode specifies whether the features of the base class are publicly inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.
  • When the base class is privately inherited by the derived class, public members of the base class becomes the private members of the derived class. Therefore, the public members of the base class are not accessible by the objects of the derived class only by the member functions of the derived class.
  • When the base class is publicly inherited by the derived class, public members of the base class also become the public members of the derived class. Therefore, the public members of the base class are accessible by the objects of the derived class as well as by the member functions of the base class.

Note:

  • In C++, the default mode of visibility is private.
  • The private members of the base class are never inherited.

C++ Single Inheritance

Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.
C++ Inheritance Where 'A' is the base class, and 'B' is the derived class.

C++ Single Level Inheritance Example: Inheriting Fields

When one class inherits another class, it is known as single level inheritance. Let's see the example of single level inheritance which inherits the fields only.
  1. #include <iostream>  
  2. using namespace std;  
  3.  class Account {  
  4.    public:  
  5.    float salary = 60000;   
  6.  };  
  7.    class Programmer: public Account {  
  8.    public:  
  9.    float bonus = 5000;    
  10.    };       
  11. int main(void) {  
  12.      Programmer p1;  
  13.      cout<<"Salary: "<<p1.salary<<endl;    
  14.      cout<<"Bonus: "<<p1.bonus<<endl;    
  15.     return 0;  
  16.  
Output:

Salary: 60000
Bonus: 5000
 
In the above example, Employee is the base class and Programmer is the derived class.

C++ Single Level Inheritance Example: Inheriting Methods

Let's see another example of inheritance in C++ which inherits methods only.
  1. #include <iostream>  
  2. using namespace std;  
  3.  class Animal {  
  4.    public:  
  5.  void eat() {   
  6.     cout<<"Eating..."<<endl;   
  7.  }    
  8.    };  
  9.    class Dog: public Animal    
  10.    {    
  11.        public:  
  12.      void bark(){  
  13.     cout<<"Barking...";   
  14.      }    
  15.    };   
  16. int main(void) {  
  17.     Dog d1;  
  18.     d1.eat();  
  19.     d1.bark();  
  20.     return 0;  
  21. }

Comments

Popular posts from this blog

Hierarchical Inheritance in C++