#include <iostream>
#define SIZE 3
using std::cout;
using std::endl;
class Mammal {
public:
Mammal() { cout << "Mammal constructor" << endl; }
virtual ~Mammal() { }
Mammal(const Mammal &m);
virtual void Print() const { cout << "class Mammal: " << endl; }
virtual Mammal *Copy() { return new Mammal(*this); }
protected:
};
Mammal::Mammal(const Mammal &m) {
cout << "Mammal Copy Constructor" << endl;
}
class Dog : public Mammal {
public:
Dog() { cout << "Dog constructor" << endl; }
virtual ~Dog() { }
Dog(const Dog & rhs);
void Print()const { cout << "class Dog: " << endl; }
virtual Mammal *Copy() { return new Dog(*this); }
};
Dog::Dog(const Dog &d) : Mammal(d) {
cout << "Dog copy constructor" << endl;
}
class Cat : public Mammal {
public:
Cat() { cout << "Cat constructor" << endl; }
~Cat() { }
Cat(const Cat &);
void Print()const { cout << "class Cat: " << endl; }
virtual Mammal *Copy() { return new Cat(*this); }
};
Cat::Cat(const Cat &c) : Mammal(c) {
cout << "Cat copy constructor" << endl;
}
int main()
{
Mammal *arr[SIZE], *p;
cout << "new Dog:" << endl;
p = new Dog;
arr[0] = p;
cout << endl << "new Cat:" << endl;
p = new Cat;
arr[1] = p;
cout << endl << "new Mammal:" << endl;
p = new Mammal;
arr[2] = p;
cout << endl;
Mammal *CopyArray[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << "arr[i]->Print(): ";
arr[i]->Print();
cout << "arr[i]->Copy(): ";
CopyArray[i] = arr[i]->Copy();
cout << endl;
}
for (int i = 0; i < SIZE; i++)
{
cout << "CopyArray[i]->Print(): ";
CopyArray[i]->Print();
cout << endl;
}
return 0;
}
/*
run:
new Dog:
Mammal constructor
Dog constructor
new Cat:
Mammal constructor
Cat constructor
new Mammal:
Mammal constructor
arr[i]->Print(): class Dog:
arr[i]->Copy(): Mammal Copy Constructor
Dog copy constructor
arr[i]->Print(): class Cat:
arr[i]->Copy(): Mammal Copy Constructor
Cat copy constructor
arr[i]->Print(): class Mammal:
arr[i]->Copy(): Mammal Copy Constructor
CopyArray[i]->Print(): class Dog:
CopyArray[i]->Print(): class Cat:
CopyArray[i]->Print(): class Mammal:
*/