If two classes are related with one another there can be two types of relationship between them. One type of relationship occurs when a class inherits another class. One type is while one class contains other class’s object as it’s data member. We have seen that while declaring a class there are data members and function members. After declaring a class we can use the object of the class as a data member of another class in the same program.
Here is the C++ program to illustrate the above feature.
#include< iostream.h >
#include< conio.h >
#include< string.h >
class carburettor
{
private:
char name[30];
char type;
float cost;
public:
void setdata(char t,float c,char *m)
{
type=t;
cost=c;
strcpy(name,m);
}
void displaydata()
{
cout<< endl<< type<< endl<< cost<< endl<< name;
}
};
class car
{
private:
char model[30],drivetype[30];
public:
void setdata(char *m,char *d)
{
strcpy(model,m);
strcpy(drivetype,d);
}
void displaydata()
{
cout<< endl<< model<< endl<< drivetype;
}
carburettor c;
};
void main()
{
clrscr();
car mycar;
mycar.c.setdata('A',1000.50,"xyz");
mycar.setdata("sports","4-wheel");
mycar.c.displaydata();
mycar.displaydata();
getch();
}
In the above C++ program the data members of the class carburettor are private, it is completely safe to embed an object of type carburettor as a public member in a new class car. To access the member functions of the carburetor class we have to use the dot operator twice.
It is more common to make the embedded objects private.
#include<iostream.h>
#include<conio.h>
class Name
{
private:
char str[20];//to store the name
char sName[20];//to store the surname
int age;
public:
void take1()
{
cout<< "\nEnter the name (With surname): -";
cin >>str >>sName;
cout<< "\nEnter the age: -";
cin >>age;
}
void display ()
{
cout<< "\nNAME:-\t"<< str<< " "<< sName;
cout<< "\nAGE:-\t"<< age;
}
};
class Details
{
private:
char town[20];
long ph_no;
Name ob;
public:
void take2()
{
ob.take1();
cout<< "\nEnter the town/city name: -";
cin>>town;
cout<< "\nEnter the Phone Number: -";
cin >>ph_no;
}
void display ()
{
ob.display ();
cout<< "\nTOWN:-\t"<< town;
cout<< "\nPHONE NUMBER:_\t"<< ph_no;
}
};
class Last:public Name,public Details
{
private:
char email[40];
public:
void take3()
{
cout<< "\nEnter the E-mail address: -";
cin >>email;
}
void display()
{
Details::display();
cout<< "\nE-MAIL ADDRESS:-\t"<< email;
}
};
void main()
{
Last o[3];
Last o[3];
int i;
clrscr ();
for(i=0;i< 3;i++)
{
o[i].take2();
o[i].take3();
}
clrscr ();
for(i=0;i< 3;i++)
{
o[i].display();
}
getch ();
}
No comments:
Post a Comment