Returning a new object on the heap

closed account (o360pfjN)
Hi all,

A quick one!

In the following code line:

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

I understanding that a new object is being created on the heap, and a pointer to it is being returned. But I don't understand why this code is valid, and I feel I should before moving on! The function is not returning a pointer, it is returning an object. What exactly is happening in order for the code to be valid?

Thanks :)

J
new Cat(*this) gives you a pointer to the new cat object. The function returns the pointer. That's it.
Last edited on
closed account (o360pfjN)
The (*this) referred to here is a parameter for a copy constructor...

Or is that not the pointer you are referring to? Do you mean another pointer which is provided as a result of creating the new Cat on the heap? Is there a conversion going on as a result of the return type?

lol clearly this will need to be spelt out a little :P
Last edited on
Your new object of cat is being created and its pointer is being returned (through Mammal* return type)...how could it possibly return an Object wen the return type is of pointer? Its not possible!
I'd like to point out that you can do this code more correct by returning pointer to a Cat object. That is

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Mammal
{
public:
   virtual !Mammal() = 0;
   virtual Mammal* Clone () const = 0;
};

Mammal::~Mammal() {}

class Cat: public Mammal
{
   virtual Cat* Clone () const { return new Cat( *this );}
};

class Dog: public Mammal 
{
   virtual Dog* Clone () const { return new Dog( *this ); }
}

Last edited on
@zuluisgrate:
You might be confused by the "*this", which is an object (a dereferenced pointer to an object, thus an object). However, the *this is simply a parameter for the constructor. The returned thing is actually the return value of "new Cat(<params>)", which is a Cat* (pointer!). Conceptually no different from doing "return new Cat(5);", but perhaps less confusing to look at.
Topic archived. No new replies allowed.