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.