I am new to c++ and would like to know what is the difference between calling a constructor with pointer and without pointer. By without pointer I mean with an instance of the class.
For example:
#include <iostream>
using namespace std;
class abc {
abc() {
cout << "constructor";
}
~abc() {
cout << "destructor";
}
};
int main() {
abc a;
return 0;
}
// VS
int main() {
abc* a = new abc();
delete a;
return 0;
}
Is the only difference that it's dynamically called and otherwise both are same, e.g. produce the same result?
abc a; allocates a on the stack, calling its default constructor. The destructor will be called when a goes out of scope.
abc* a = new abc(); allocates memory for an abc object on the heap, calls its default constructor and returns a pointer to the object. Remember to call delete a; (which will call the destructor) else you'll leak memory.
abc a(); is a function prototype for a function called a that returns an abc, taking no parameters.
class {
....
}abc;
abc a;
abc *a = new abc();
In both situation the class constructor is called because you are instantiating an object. But there are a few other subtle differences.
abc a;
Here the object is allocated on the stack (if you declare it in your main or other function), OR in the .data section if you declare it globally. Either case the memory is allocated statically; there is no memory management to worry about.abc *a = new abc(); Now you are allocating memory dynamically for your object and you need to take care of the memory management yourself, i.e. call delete() or have e memory leak in your program.But there is one other difference between the two ways of instantiating your object: in the second example you are also calling operator new. Which can be overloaded to give you a different behavior. Also because the second call involves operator new, you can use placement new and allocate your object in a memory location of your choosing - you cannot do this with the first example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With