In this tutorial we learn the concept of Inheritance in c++.
Inheritance is the most powerful feature in the c++ language
that allows us to the code re usability. That is better for every programmer
when we are required the data again and again
then instead of writing that code again use inheritance. This feature save
the time as well as money and also increases the reliability.
Que:What is mean by Inheritance?
Ans: The inheritance is the creating a new class form
already exiting class. The old or existing class is known as Base class (super
class or parent class) and the new class is known as Derived class(child class
or sub class.
Types of Inheritance:
1)Single Inheritance
2)Multiple Inheritance
2)Multiple Inheritance
3)Multilevel Inheritance
4)Hierarchical Inheritance
5)Hybrid Inheritance
Here we learn first Single Inheritance:
This type of
Inheritance is done when the new class is creating only a one Base class. The
Inheritance feature is allows us to use the data of the parent class.
Class base-Class
{
…………………
………………..
};
Class derived-class:base-class
…………………….;
……………………;
}
The following code shows the single inheritance of student
and teacher class in this code Teacher is the super class and the Student is
the drived class. The Student class is uses the feature of the Teacher class.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class Teacher
{
char
name[20];
public:
char
sub[20];
void
getdata()
{
cout<<"\nFor
Teacher:";
cout<<"\nEnter
Teacher Name:";
gets(name);
cout<<"\nEnter
subject:";
gets(sub);
}
void
display()
{
cout<<"\n*****Teacher
Information*****";
cout<<"\nName:"<<name;
cout<<"\nSubject:"<<sub;
}
};
class Student:public Teacher
{
char
sname[20],cls[20];
int
rno;
public:
void
getinfo()
{
getdata();
cout<<"\nFor
Student:";
cout<<"\nEnter
Student Name:";
gets(sname);
cout<<"\nEnter
class of Student:";
gets(cls);
cout<<"\nEnter
roll no of Student:";
cin>>rno;
}
void
show()
{
display();
cout<<"\n*****Student
Information*****";
cout<<"\nName:"<<sname;
cout<<"\nClass:"<<cls;
cout<<"\nRoll
No.:"<<rno;
}
};
void main()
{
Student
s1;
clrscr();
s1.getinfo();
s1.show();
getch();
}
The following code shows the OUTPUT:
No comments:
Post a Comment