Saturday 2 October 2010

HIERARCHICAL INHERITANCE




HIERARCHICAL INHERITANCE:
When two or more classes are derived from the same base class ,the inheritance type is called as hierarchical inheritance.
Syntax:
The general form of hierarchical inheritance is as follows:
class<derived class name1>:<access specifier><base class name>
class <derived class name 2>:<access specifier><base class name>
In this inheritance from a single base class many child classes are derived so the member variables and member functions of base class are inherited to all the child classes.
In the above pictorial representation A is the base class and the classes B, C, D are the derived classes. Here the derived classes are not used for deriving other classes.
Example 5:
#include<iostream.h>
#include<conio.h>
class A
{
private:
int a;
public:
void setA(int x)
{
a=x;
}
void showA()
{
cout<<”\n A=”<<a;
}
};

class B:public A
{
private:
int b;

public:
void setB(int x)
{
b=x;
}
void showB()
{
cout<<”\n B=”<<b;
}
};

class C:public A
{
private:
int c;
public:
void setC(int x)
{
c=x;
}
void showC()
{
cout<<”\nC=”<<c;
}
};
void main()
{
A objA;
B objB;
C objC;
clrscr();

//calling class A methods
cout<<”\n calling class A methods”;
objA.setA(10);
objA.show();

//calling class B methods
cout<<”\n calling class B methods”;
objB.setA(10);
objB.setB(20);
objB.showA();
objB.showB();

//calling class C methods
cout<<”\n calling class C methods”;
objC.setA(10);
objC.setC(30);
objC.showA();
objC.showC();
}

Output:
Calling class A methods
A=10
Calling class B methods
A=10
B=20
Calling class C methods
A=10
C=30

The above program is an example of hierarchical inheritance. In this example class B, class C are inherited from the same base class A. so class B will have the members of class B and members of class A and class C will have the members of class C and class A.



Types of Inheritance

No comments:

Post a Comment