We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13
Prepared By
Prashant Soni Assistant Professor,UCER Naini,Allahabad
Object Oriented System Design
Unit 5, Lecture 3 Inheritance C++ Single Inheritance • Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class. C++ Single Level Inheritance Example: Inheriting Fields #include <iostream> using namespace std; class Account { public: float salary = 60000; }; class Programmer: public Account { public: float bonus = 5000; }; int main(void) { Programmer p1; cout<<"Salary: "<<p1.salary<<endl; cout<<"Bonus: "<<p1.bonus<<endl; return 0; } #include <iostream> using namespace std; class Animal { public: void eat() { cout<<"Eating..."<<endl; } }; class Dog: public Animal { public: void bark(){ cout<<"Barking..."; } }; int main(void) { Dog d1; d1.eat(); d1.bark(); return 0; } How to make a Private Member Inheritable
• The private member is not inheritable.
• If we modify the visibility mode by making it public, but this takes away the advantage of data hiding. • C++ introduces a third visibility modifier, i.e., protected. • The member which is declared as protected will be accessible to all the member functions within the class as well as the class immediately derived from it. Visibility modes can be classified into three categories • Public: When the member is declared as public, it is accessible to all the functions of the program. • Private: When the member is declared as private, it is accessible within the class only. • Protected: When the member is declared as protected, it is accessible within its own class as well as the class immediately derived from it. Multilevel Inheritance Multilevel inheritance is a process of deriving a class from another derived class. When one class inherits another class which is further inherited by another class, it is known as multi level inheritance in C++. Inheritance is transitive so the last derived class acquires all the members of all its base classes. #include <iostream> using namespace std; class Animal { public: void eat() { cout<<"Eating..."<<endl; } }; class Dog: public Animal { public: void bark(){ cout<<"Barking..."<<endl; } }; class BabyDog: public Dog { public: void weep() { cout<<"Weeping..."; } }; int main(void) { BabyDog d1; d1.eat(); d1.bark(); d1.weep(); return 0; } Multiple Inheritance • Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more classes. C++ Hybrid Inheritance • Hybrid inheritance is a combination of more than one type of inheritance. C++ Hierarchical Inheritance • Hierarchical inheritance is defined as the process of deriving more than one class from a base class.