Good evening,..
i missed my last cpp lecture and can't understand few thing i hope you can explain it (the other classmates didn't understand it aswal so i went to you guys )
she gave a code and said :
there are two type of heritage :
compostion:
works like "has a " and "is part of" : a computer is the some of it components (IO,CPU,BUS,storage device,...);
aggretion.
no info at all
Inheritance:
work like "is a" : a chief excuter is type of an manger that is type of an employe.
here is example for :
compostion (sorry for the indent style i just copy paste it (im afraid to some how make it less understandable));
Code:
…….
#include <cstring>
class Engine{
char* model;
int volume;
public:
Engine(char* Model="UNKNOWN",int Volume=0)
{
model=new char[strlen(Model)+1];
if(model) strcpy(model,Model);
else return;
volume=Volume;
}
~Engine()
{if(model) delete model;}
void Print()
{ cout<<model<<" "<<volume<<endl; }
};
class Car{
char* color;
int year;
Engine eng;
public:
Car(char* Model="UNKNOWN",int Volume=0,char* olor="UNKNOWN",
int Year=1):eng(Model,Volume)
{
color=new char[strlen(Color)+1];
if(color)
strcpy(color,Color);
year=Year;
}
~Car() {if(color) delete color;}
void Print()
{
cout<<color<<" "<<year<<endl;
eng.Print();
}
};
int main()
{
char buf_mod[100],buf_color[100];
int year,volume;
cout<<"enter data :”; cin>>buf_mod>>year>>buf_color>>volume;
Car p(buf_mod,year,buf_color,volume);
p.Print();
}
and an example for Aggregation.
Code:
class Point
{
int x,y;
public:
Point(int _x,int _y){x=_x; y=_y;}
~Point(){}
void Print()
{ cout<<x<<" "<<y<<endl;}
};
class Line
{
Point *p1,*p2;
public:
Line(int x1,int y1,int x2,int y2)
{
p1=new Point(x1,y1);
p2=new Point(x2,y2);
}
/*Line(int x1,int y1,int x2,int y2):p1(new Point(x1,y1)),p2(p2=new Point(x2,y2))
{ }*/
~Line()
{if(p1) delete p1;if(p2) delete p2;}
void Print()
{
cout<<" p1 :";p1->Print(); cout<<" p2 :";
p2->Print();
}
};
int main()
{
Line l1(1,2,10,20),*l_ptr;
l_ptr=new Line(1,2,3,4);
l_ptr->Print();
l1.Print();
delete l_ptr;
}
i can't realy get the idea what is the defrence ..
if in both i transfer all the func and from the base class to the new class what is the defrance.
could you plese try to provide a little more understandble class that will show the diffrence
in Dietel's book i didn't even found does types.
thnx in advance..