CHAPTER 7 : OVERLOADED, POLYMORPHISM, COMPOSITION |
void
show (double val){
cout << " double " << val << endl;
}
void
show (char *val) {
cout << " string " << val << endl;
}
int
main(){
show(12);
show(3.1415);
show(" Hello world");
return 0;
}
CONSTRUCTOR OVERLOADING
COPY CONSTRUCTOR
TAnyClass::TAnyClass(TAnyClass
©){
cout << "\ninside TAnyClass's copy constructor\n";
i = copy.i;
r = copy.r;
if (copy.s)
s = strdup(copy.s)
else
s = NULL;
}
main(){
TAnyClass v1;
TAnyClass v2(1,2, " a test string ");
TAnyClass v3 = v2;
}
POLYMORPHISM
class
derived1 : public base{
public:
derived(int x) : base(x) {}
void func(){
cout << " using derived1's version of func() : ";
cout << i*i << endl;
}
};
class
derived2 : public base {
public:
derived2(int x) : base (x) {}
void func(){
cout << "using derived2's version of func():";
cout << i + i << endl;
}
};
main()
{
base *p;
base ob(10);
derived1 d_ob1(10);
derived2 d_ob2(10);
p = &ob;
p->func(); //use base's func()
p = &d_ob1;
p->func(); //use derived1's func()
p = &d_ob2;
p->func(); //use derived2's func()
return 0;
}
class
derived1 : public base{
public:
derived1(int x) : base(x){}
void func(){
cout << "using derived1's version of func():";
cout << i * i << endl;
}
};
class
derived2 : public base{
public:
derived2(int x) : base(x) {}
//derived2 does not override func()
};
main() {
base *p;
base ob(10);
derived1 d_ob1(10);
derived2 d_ob2(10);
p = &ob;
p->func(); //use base's func()
p = &d_ob1;
p->func(); //use derived1's func()
p = &d_ob2;
p->func(); //use derived2's func()
return 0;
}
main(){
TValue *basep;
basep = new TValue (10);
cout << basep ->GetValue() << endl;
delete basep;
basep = new TMult(10,2);
cout << basep->GetValue() << endl;
delete basep;
return 0;
}
PURE VIRTUAL FUNCTION
#include <iostream.h>
class
Date{
int month, day, year;
public:
Date(int,int,int);
void print();
};
Date::Date(int
m,int d,int y){
month=m;
day=d;
year=y;
cout<<"Date object constructor:"<<endl;
}
void
Date::print(){
cout << month << day<< year;
}
class
child{
private:
char *name; Date birthday; Date regdate;
public:
child(char*, int, int,int,int,int,int);
void print(void);
};
child::
child(char *nama,int bm, int bd, int by, int rm, int rd, int ry)
:birthday(bm,bd,by), regdate(rm,rd,ry){
name=nama;
cout<<"child object constructor:"<< name;
}
void
child:: print(){
cout<<"\nchild name:"<< name;
cout<<"\nBirthdate:";birthday.print();
cout<<"\nRegister date for school:"; regdate.print();
}
main(){
child a ("azman",10,11,92,1,1,99);
a.print();
return 0;
}
Anda dikehendaki sentiasa menyemak latihan lab anda dari masa ke semasa