Inheritance is the process by which the object of a derived or sub class can acquire the properties of an existing class. Suppose we want to change the above program so that it’s object will contain another long type variable to store the phone number. It is not always possible to modify the class. So we inherits the properties of the object of the above class (here person) to another class Phone and add new features in the class Phone. Ultimately we will create objects of class Phone.
Here is the sample C++ program on Inheritance.
#include< iostream.h>
#include< stdio.h>
#include< conio.h>
class person
{
protected:
char name [40];
public:
void setName ()
{
puts ("Enter Name: -");
gets (name);
}
};
class Phone: public person /* class Phone is a derived class of person*/
{
private:
long phone_no;
public:
void getPhone ()
{
cout<< "Enter the Phone Number: -";
cin >>phone_no;
}
void display ()
{
cout<< "\nName is: -"<< name;
cout<< "\t"<< phone_no;
}
};
void main ()
{
clrscr ();
Phone p;
Phone *ptr [10];
int n=0;
char choice;
do
{
ptr [n]=new Phone;
ptr [n]->setName ();
ptr [n]->getPhone ();
n++;
fflush (stdin);
cout<< "Another (y/n): -";
cin >>choice;
} while (choice=='y');
for (int i=0;i< n; i++)
{
ptr [i]->display ();
}
getch ();
}
No comments:
Post a Comment