If two classes are related with one another there can be two kinds of relationship between them.
- kind of relationship
- has a relationship
kind of relationship is supported by inheritance.
has a relationship is supported by composition or containership.
In Inheritance if a class Y is derived from Class X,we can say that "Class Y is a kind of Class X". This is because class Y has all the characteristics of X, and in addition some of its own.
For this reason inheritance is often called a kind of relationship.
In has a relationship you simply create objects of your existing class inside the new class.
Example 1:
class company
{
};
class employee
{
company c;
};
Example 2:
#include<iostream.h>
#include<string.h>
class carburettor
{
private:
char type;
float cost;
char mfr[20];
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[20];
char drivetype[20];
public:
void setdata(char *m,char *d)
{
strcpy(model,m);
strcpy(drivetype,d);
}
void displaydata()
{
cout<<endl<<model<<endl<<drivetype;
}
carburettor c; //embedded object
};
void main()
{
car mycar;
mycar.c.setdata('A',6500.00,"Hund");
mycar.setdata("sports","4-wheel");
mycar.c.displaydata();
mycar.displaydata();
}
C++ has much more sophisticated mechanisms for code reuse in the form of composition and inheritance.
Composition is useful when classes act like a data type.
No comments:
Post a Comment