since I’ve came from c# to c++ everything looks crazy for me in c++.
I just wondering If someone could explain me why do we have these kind of instantiating in c++ :
method 1:
ClassA obj1; // this is going to stack
method 2:
ClassA *obj1 = new ClassA(); //this is going to heap
whereas we don’t have the common instantiating in C# way on c++ :
ClassA obj2 = new obj2();
and one more question in method1 I get an instance from the ClassA but without the () and this is the exact place the I’ve got confused , why do we have to instatiating like that?
our ClassA has an constructor but instantiating without parentheses???
how come we call its constructor?
p.s : I’ve read these topics :
Different methods for instantiating an object in C++
Indeed moving to C++ from a language like Java or C# can be daunting, I’ve gone through it as well.
The first and foremost difference is that in C++ you almost always manage your own memory. When creating an object on the heap you are responsible for deleting it so it does not leak memory – this in turn means you can delete it when you see fit. When creating an object on the stack, it is automatically deleted when it goes out of scope – you must be careful not to use it after it goes out of scope.
Example:
versus
That being said, the two methods are also significantly different in one aspect: the first one creates an object. The second one creates a pointer to an object. The nice thing about having pointers is that you can pass them around as parameters with only minimal memory being copied on the stack (the pointer is copied, instead of the whole object). Of course, you can always get the address of an object allocated on the stack by using “&”, or pass it around as a reference – however, when using objects allocated on the stack you much be especially careful with their scope.
I’ve found this website a great resource when I moved from Java to C++: http://www.parashift.com/c++-faq-lite/ – you will probably find it too, it offers a lot of good explanations