Professional Documents
Culture Documents
Introduction
The mechanism of deriving a new class from an old one is called inheritance (or derivation) (Balagurusamy) The old class called base class and the new class called derived class or subclass Often referred to as an is-a relationship because every object of the class being defined is also an object of the inherited class
Types of Inheritance
Single Inheritance
Multiple Inheritance
Hierarchical Inheritance
Multilevel Inheritance
Hybrid Inheritance
Example
Ba e la S e S ape De e la e G a a eS e U e a a eS le a le Re a le Ca L a H me mp eme L a M a eL a Fa l Mem e S a Mem e C e k A Sa A C e
L a
Empl ee A
Derived lass
class derived-class-name : visibility-mode base-class-name { //Members of derived class ... };
Example:
class ABC :private XYZ //private derivation { //members of ABC }; class ABC :public XYZ //public derivation { //members of ABC }; class ABC : XYZ //private derivation by default { //members of ABC };
Single Inheritance
class base //base class { public: int id; void get_id() { cout<<"\nEnter your id: "; cin>>id; } void display_id() { cout<<"I'm from base class and my id = "<<id<<"\n"; } };
class derived : public base //derived class { public: float age; void get_age() { cout<<"\nEnter your age: "; cin>>age; } void display_age() { cout<<"I'm from derived class and my id = "<<id<<"\n"; cout<<"I'm from derived class and my age = "<<age<<"\n"; } }; main() { derived d; d.get_id(); d.get_age(); //cout<<"\nI am from main and my id is: "<<d.id<<"\n"; d.display_id(); d.display_age(); }
What if you ma e id private? What if you inherit the base class privately? Or ow can you inherit base class privately? What if base class and derived class define a function of the same name ?
The base class function will be called only if the derived class does not redefine the function
Multilevel inheritance
The chain ABC is nown as inheritance path Code Example
Multiple Inheritance
Code Example
Hierarchical Inheritance
Hybrid Inheritance
Code Example