inheritance slides
TRANSCRIPT
Types of inheritance
There are 2 types of inheritance as shown below.1. Single Inheritance2. Multiple Inheritance
1. Single inheritance:
There are 3 types of single inheritance1. Simple Inheritance2. Multilevel Inheritance3. Hierarchical Inheritance
Multilevel Inheritance
• Class derived from another derived class• Class B derived from A and Class C derived
from B
Syntax:
Example of multilevel inheritance: class A //base class class B : public A class C : public B
Multiple inheritance
• Class derived from more than one base class• Class C inherit features of A and B
Syntax:
Example of multiple inheritance: class A //base class class B //base class class C : public A , B //derived class
Hierarchical Inheritance
• More than one classes derived from single class• All classes inherit features of class A
syntax:
Example of hierarchical inheritance: class A //base class class B : public A class C : public A
Constructor and destructor calling:
Constructor:–• Derived class constructor is called to create
derived class object• Invokes base class constructor before derived
class initializer list & constructor bodyDestructor:–• Destructor are called in Reverse order of constructor • Derived class destructor body is executed first• Then destructors body of base class executed
Derived-class Object
Derived-class constructor invokes base class constructor either• Implicitly • Explicitly
Implicit callclass B { public: B(){cout<<"Construct B";} ~B(){cout<<"Destruct B”; } };class D: public B{ public: D(){cout<<"Construct D";} ~D(){cout<<"Destruct D";} };int main(){ D obj; //object of derived class}
Explicit callclass B { public: int x; B(int i) { x=i; cout<<“parameterize constructor B”; }};Class D: public B{ public: int y; D(int j) :B(j){ y=j; cout<<“parameterize constructor D”; }};
output:
int main(){ D obj(5); //object of derived class cout<<obj.x<<endl;}
Parameterize constructor BParameterize constructor D5
When a program creates a derived-class object
The derived-class constructor immediately calls the base-class constructor,
The base-class constructor’s body executes, Then the derived class’s member initializers
execute, and Finally the derived-class constructor’s body
executes