Modes of Inheritance

Public mode: Mode of inheritance public means public member of base class becomes public in derived class and protected member of base class becomes protected in derived class.  

Public member of base class will become public member in derived class

protected member of base class will become protected member in derived class 

Protected mode:   Mode of Inheritance protected means  both public member and protected members of the base class will become protected in derived class.

Both public and protected member of Base class will become protected in derived class

Private mode:  Mode of Inheritance Private means  both public member and protected members of the base class will become Private in derived class.

Both public and protected member of the Base class will become Private member in derived class


Types of Inheritance:

There are following types of Inheritance:

1) Single Inheritance:  Single inheritance allowed to inherit from only one class. That means there will be only one base class and one derived class only as shown in below fig

Note : The private members in the base class cannot be directly accessed in the derived class, while protected members can be directly accessed. For example, Classes B, C and D all contain the variables x, y and z in below example. It is just question of access.



Ex 1:
class  B1
public: 
    int m; 
protected: 
    int n; 
private: 
    int x; 
}; 
class D1 : public B1 
    // m is public 
    //  n is protected 
    // x is not accessible from B1 class  
}; 


Example of Single Level Inheritance

In this example StaffAcc is a base class name while Programmer is the derived class. Since mode of inheritance is public so public member  StaffSal of base class will also be public member of derived class along with Programmer class. Therefore object Prog1 of Programmer class can access both public member in Programmer class in main function as below.

class   StaffAcc {  
   public:  
   float   Staffsal = 60000;   
 };  
   class Programmer: public StaffAcc {  
   public:  
   float ProgBonus = 5000;    
   };       
int main(void) 
     {  
     Programmer  Prog1;  
     cout<<" Programmer Salary: "<<Prog1.Staffsal<<endl;    
     cout<<" Programmer Bonus: "<<Prog1.ProgBonus<<endl;    
    return 0;  
     } 







Output :
Programmer Salary : 60000
Programmer Bonus : 5000



Please Give me your feedback in comment how much effective this blog for you.


Comments

Post a Comment