views:

84

answers:

4

In C++ do you always have initialize a pointer to an object with the new keyword?

Or can you just have this too:

MyClass *myclass;

myclass->DoSomething();

I thought this was a pointer allocated on the stack instead of the heap, but since objects are normally heap allocated, I think my theory is probably faulty??

Please advice.

+5  A: 

No you can not do that, MyClass *myclass will define a pointer (memory for the pointer is allocated on stack) which is pointing at a random memory location. Trying to use this pointer will cause undefined behavior.

In C++, you can create objects either on stack or heap like this:

MyClass myClass;
myClass.DoSomething();

Above will allocate myClass on stack (the term is not there in the standard I think but I am using for clarity). The memory allocated for the object is automatically released when myClass variable goes out of scope.

Other way of allocating memory is to do a new . In that case, you have to take care of releasing the memory by doing delete yourself.

MyClass* p = new MyClass();
p->DoSomething();
delete p;

Remeber the delete part, else there will be memory leak.

I always prefer to use the stack allocated objects whenever possible as I don't have to be bothered about the memory management.

Naveen
+4  A: 

Hi,

if you want the object on the stack, try this:

MyClass myclass;
myclass.DoSomething();

If you need a pointer to that object:

MyClass* myclassptr = &myclass;
myclassptr->DoSomething();
kotlinski
A: 
  1. MyClass myclass -> Stack allocated. No need for new
  2. MyClass *myclass -> Heap allocated. new is necessary. You cannot do myclass->DoSomething() unless memory is allocated. It shall produce undefined behavior. Or point it to a stack allocated object instead
bdhar
+2  A: 

No, you can have pointers to stack allocated objects:

MyClass *myclass;
MyClass c;
myclass = & c;
myclass->DoSomething();

This is of course common when using pointers as function parameters:

void f( MyClass * p ) {
    p->DoSomething();
}

int main() {
    MyClass c;
    f( & c );
}

One way or another though, the pointer must always be initialised. Your code:

MyClass *myclass;
myclass->DoSomething();

leads to that dreaded condition, undefined behaviour.

anon
Good answer, although shouldn't line three read `myclass = ...`? As it is now you are dereferencing an invalid pointer and giving it the address of c, or am I just in dire need of caffeine?
Skurmedel
@Skurmedel Of course it should - thanks.
anon