Virtual Copy Constructors - C++ Class

C++ examples for Class:Inheritance

Description

Virtual Copy Constructors

Demo Code

                                                                     
#include <iostream> 
                                                                        
class Pet //from  w  w  w  .j  a v a  2s.com
{ 
public: 
    Pet():age(1) { std::cout << "Pet constructor ...\n"; } 
    virtual ~Pet() { std::cout << "Pet destructor ...\n"; } 
    Pet (const Pet &rhs); 
    virtual void speak() const { std::cout << "Pet speak!\n"; } 
    virtual Pet* clone() { return new Pet(*this); }  
    int getAge() const { return age; } 
                                                                        
protected: 
    int age; 
}; 
                                                                        
Pet::Pet (const Pet &rhs):age(rhs.getAge()) 
{ 
    std::cout << "Pet copy constructor ...\n"; 
} 
                                                                        
class Dog : public Pet 
{ 
public: 
    Dog() { std::cout << "Dog constructor ...\n"; } 
    virtual ~Dog() { std::cout << "Dog destructor ...\n"; } 
    Dog (const Dog &rhs); 
    void speak() const { std::cout << "Woof!\n"; } 
    virtual Pet* clone() { return new Dog(*this); } 
}; 
                                                                        
Dog::Dog(const Dog &rhs): 
Pet(rhs) 
{ 
    std::cout << "Dog copy constructor ...\n"; 
} 
                                                                        
class Cat : public Pet 
{ 
public: 
    Cat() { std::cout << "Cat constructor ...\n"; } 
    virtual ~Cat() { std::cout << "Cat destructor ...\n"; } 
    Cat (const Cat&); 
    void speak() const { std::cout << "Meow!\n"; } 
    virtual Pet* Clone() { return new Cat(*this); } 
}; 
                                                                        
Cat::Cat(const Cat &rhs): 
Pet(rhs) 
{ 
    std::cout << "Cat copy constructor ...\n"; 
} 
                                                                        
enum ANIMALS { MAMMAL, DOG, CAT}; 
const int numAnimalTypes = 3; 
int main() 
{ 
    Pet *array[numAnimalTypes]; 
    Pet *ptr; 
    int choice, i; 
    for (i = 0; i < numAnimalTypes; i++) 
    { 
             std::cout << "(1) dog (2) cat (3) mammal: "; 
             std::cin >> choice; 
             switch (choice) 
             { 
             case DOG:  
                  ptr = new Dog; 
                  break; 
             case CAT:  
                  ptr = new Cat; 
                  break; 
             default:  
                  ptr = new Pet; 
                  break; 
             } 
             array[i] = ptr; 
    } 
    Pet *otherArray[numAnimalTypes]; 
    for (i=0; i < numAnimalTypes; i++) 
    { 
             array[i]->speak(); 
             otherArray[i] = array[i]->clone(); 
    } 
    for (i=0; i < numAnimalTypes; i++) 
    { 
             otherArray[i]->speak(); 
    } 
    return 0; 
}

Result


Related Tutorials