0

While reading "Sams teach yourself c++ in 21 days" I cannot understand how does virtual copy constructor work. Full code from book is here: [http://cboard.cprogramming.com/cplusplus-programming/9392-virtual-copy-constructor-help.html][1]

Especially virtual method Clone() calls Mammal copy constructor and Dog copy constructor because it returns "Mammal*" and returns "new dog (*this)"

  Mammal::Mammal(const Mammal &rhs):itsAge(rhs.GetAge())
    {
    cout <<  "Mammal copy constructor\n";
    };

Dog::Dog (const Dog &rhs):Mammal(rhs) //what is ":Mammal(rhs)" here -     
                                      // call of Mammal copy constructor?  
                                      //if not why is it required?
                                      //or what is it here?
{
    cout << "Dog copy constructor\n";
}; 

And what does return "return new Dog(*this)"? new object or pointer at new object?

Thank you for your answers. P.S. Sorry for my previous answer with wrong tags. It is my first experience of using 'stackoverflow"

user2553675
  • 495
  • 2
  • 5
  • 16

1 Answers1

0
Dog(*this); 

creates an object of type Dog by calling the copy constructor. Since Dog derives from Mammal, the Mammal constructor is called. In particular, you can see from this code

Dog::Dog(const Dog & rhs):
Mammal(rhs)

that the copy constructor of Mammal gets called, which is passed rhs as a parameter.

new Dog(*this);

returns the pointer to a heap-allocated object of type Dog, which is initialized using the copy constructor (see above). When

virtual Mammal* Clone() { return new Dog(*this); }

gets called, the Dog* returned by the new operator gets converted to a Mammal* and returned.

Stefano Falasca
  • 8,837
  • 2
  • 18
  • 24