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. PS Sorry for my previous answer with wrong tags. It is my first experience of using 'stackoverflow"
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.