simple question about objects and pointers

why they always use
class_name *pointer = new class_name(arg)
pointer->member()

instead of
class_name object = new class_name(arg)
object.member()

im sorry im learning c++ after c# which makes this kinda confusing to me
the first we create pointer to a new object then we use it to access member/method
the second we create the object striaght then use it directly

what is the difference ? do i got it right ? which is more efficient ?
In C++ class objects can be defined either in stack or in heap. In C# class objects always are allocated in heap.
In C++ you should yourself delete objects created in heap. in C# it is the garbage collector that removes objects from the heap.

So consider the following C++ code that would not use pointers

MyClass obj1;

MyClass obj2 = new myClass();

How will you distinguish obj1 and objj2 whether the object requires to be deleted or not?
Last edited on
i still didn't get what you said at the end and the difference between them (sorry the book im using is too dry)

which expression in c++ create in heap and which create in stack ? and which is better or what is the use of both ?
and i duno the answer of the last question , please lemme know if you don't mind
thank you so much :)
Hi,

in Vlad from moscow's example

MyClasss obj1;
would be created on the stack

whereas:
myClass *obj2 = new myClass();

Would be created on the heap,

the key difference here is that as the flow of execution leaves the function where obj1 has been created, it will be popped from the stack, and removed from memory.

obj2 however will not be removed from memory when it goes out of scope and will need to be explicitly deleted again when it is no longer needed.

As Vlad said, C# has garbage collection and would be able to detect when obj2 is no longer needed and would remove it for you, where C++ does not.

The advantage of using the pointers is that you are juggling with an address to an instance instead of the instance its self,

so if I were to write:

MyClasss *ptr_a = new MyClass();
MyClasss *ptr_b = null;
then write
ptr_a->name ="ptr_a";

ptr_b = ptr_a;
ptr_b->name ="ptr_b";

std::cout<<ptr_a->name<<std::endl;
std::cout<<ptr_b->name<<std::endl;


then both ptr_a and ptr_b would be pointing to the same "instance" of MyClass in memory
so the print out from this would say:
"ptr_b"
"ptr_b"

but if i were to write
MyClasss obj1;
MyClasss obj2;

obj1.name ="obj1";
obj1 = obj2;

obj2.name ="obj2";

std::cout<<obj1.name<<std::endl;
std::cout<<obj2.name<<std::endl;

we would have two copies of MyClass in memory so the print out from this would read
"obj1"
"obj2"

Thanks -NGangst
Last edited on
Topic archived. No new replies allowed.