Class Constructors

The subject of different types of class constructor seems pretty nuanced (to me at least).

I’d appreciate it if someone could take a crack at explaining the difference between these invocations:

myClass myObject1(1);
myClass myObject2 = myClass(2);
myClass *myObject3 = new myClass(3);

I'm thinking that the first two invocations will place the object in the Globals area or the Stack (depending on where used). The third use will create the object in the heap. But, what other differences are there?

Thanks.

gfvalvo:

myClass *myObject3 = new myClass(3);

It is my understanding that in this case you are creating a myClass pointer on the stack pointing to a myClass object on the heap.

we are outside a method, I assume...

BulldogLowell:
It is my understanding that in this case you are creating a myClass pointer on the stack pointing to a myClass object on the heap.

we are outside a method, I assume...

Yes, I agree: Pointer variable on stack pointing to object in heap. Unless, of course, the pointer variable was defined as global.

What about the difference (if any) between the other two invocations?

myClass myObject1(1);
myClass myObject2 = myClass(2);

Let's assume they are living in Global Land outside of any function.

Thanks.

gfvalvo:
What about the difference (if any) between the other two invocations?

myClass myObject1(1);

myClass myObject2 = myClass(2);

well, what's happening in the 2nd that isn't in the first?

The first line creates a new object on the stack by calling the constructor myClass(myargs).

there is more to the 2nd one:

  • Create a myClass object by calling the constructor myClass(myargs).
  • Create a myClass object using the constructor myClass(const myClass&) (i.e. Copy Constructor)
  • Call ~myClass() on the object created in the 1st step

As mentioned, I was thinking about these as definitions of global objects. So, they'll probably go in the Global memory area rather than on the stack. But, thanks for your explanation of the constructor / destructor action, that's what I was really interested in.

It's unclear to me that there would be any good reason to use the second method when doing a static definition of a global object.

gfvalvo:
... they'll probably go in the Global memory area rather than on the stack.

yeah

gfvalvo:
It's unclear to me that there would be any good reason to use the second method when doing a static definition of a global object.

I'm assuming that the compiler would probably optimize the 2nd method away :wink: