If two classes are related with one another there can be two types of relationship between them : a kind of relationship and a has a relationship. The kind of relationship is supported by inheritance and a has a relationship is supported by composition or containership.
In Inheritance if a class Y derived from class X, we can say that the new class Y is like that old class X or "Y is a kind of X". This is because the class Y has all the characteristic of X & in addition of its own.
In a has a relationship you simply create objects of your existing class inside the new class . For example, if there is a class called carburettor we can create an object of this class in the new class as shown below:
class carburettor.
{
};
class car
{
carburettor c;
} ;
Ex:
#include<iostream.h>
#include<string.h>
class carburettor
{
private:
char type;
float cost;
char mfr[30];
public:
void setdata(char t,float c,char*m)
{
type=t;
cost=c;
strcpy(mfr,m);
}
void displaydata()
{
cout<<endl<<type<<endl<<cost<<endl<<mfr;
}
};
class car
{
private: char model[25];
char derivetype[20];
public: void setdata(char *m,char *d)
{
strcpy(model,m);
strcpy(derivetype,d);
}
void displaydata()
{
cout<<endl<<model<<endl<<derivetype;
}
carburettor c;//embedded object
};
void main()
{
car mycar;
mycar.c.setdata('A',8500,"Micro");
mycar.setdata("sports","4-wheel");
mycar.c.displaydata();
mycar.displaydata();
}
In Inheritance if a class Y derived from class X, we can say that the new class Y is like that old class X or "Y is a kind of X". This is because the class Y has all the characteristic of X & in addition of its own.
In a has a relationship you simply create objects of your existing class inside the new class . For example, if there is a class called carburettor we can create an object of this class in the new class as shown below:
class carburettor.
{
};
class car
{
carburettor c;
} ;
Ex:
#include<iostream.h>
#include<string.h>
class carburettor
{
private:
char type;
float cost;
char mfr[30];
public:
void setdata(char t,float c,char*m)
{
type=t;
cost=c;
strcpy(mfr,m);
}
void displaydata()
{
cout<<endl<<type<<endl<<cost<<endl<<mfr;
}
};
class car
{
private: char model[25];
char derivetype[20];
public: void setdata(char *m,char *d)
{
strcpy(model,m);
strcpy(derivetype,d);
}
void displaydata()
{
cout<<endl<<model<<endl<<derivetype;
}
carburettor c;//embedded object
};
void main()
{
car mycar;
mycar.c.setdata('A',8500,"Micro");
mycar.setdata("sports","4-wheel");
mycar.c.displaydata();
mycar.displaydata();
}
No comments:
Post a Comment