Write a C++ program to incorporate Heirarchial Inheritance.
AIM:
Write a C++ program to incorporate Heirarchial Inheritance.
THEORY:
In Object Oriented Programming, the
root meaning of inheritance is to establish a relationship between
objects. In Inheritance, classes can inherit behaviour and attributes
from pre-existing classes, called Base Classes or Parent Classes. The resulting classes are known as derived
classes or child classes.
So in Hierarchical Inheritance, we have 1 Parent Class and Multiple Child Classes, as shown in the pictorial representation given on this page, Inheritance. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level. One example could be classification of accounts in a commercial bank or classification of students in a university.
In C++, such problems can be easily converted into
hierarchies. The base class will include all the features that are common to
the subclasses. A subclass can be constructed by
inheriting the properties of the base class. A subclass can serve as a base
class for the lower level classes and so on.
A
derived class with hierarchical inheritance is declared as follows:
class
A {.....}; // Base class
class
B: public A {.....}; // B derived
from A
class
C: public A {.....}; // C derived
from A
This process can be extended to any number of levels.
Let us understand this concept by a simple C++ program:
SOURCE CODE:
nclude<iostream>
using namespace std;
class A
{
protected:
char
name[10];
int
age;
};
class B:public A
{
public:
int
h,w;
void
get_data1()
{
cout<<"\n
enter name:";
cin>>name;
cout<<"\n
enter weight and height:";
cin>>w>>h;
}
void
show()
{
cout<<name<<endl<<w<<endl<<h<<endl;
}
};
class C:public A
{
public:
char
gender;
void
get_data2()
{
cout<<"\n
enter age:";
cin>>age;
cout<<"enter
gender:";
cin>>gender;
}
void
show()
{
cout<<age;
cout<<gender;
}
};
int main()
{
B ob;
C ob1;
ob.get_data1();
ob1.get_data2();
ob.show();
ob1.show();
}
Labels: oop through c++ lab
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home