When I create an object of a class, say,
class A {
public: A() {}
};
A a;
Is only the constructor called? Or is it that the new
operator is used implicitly?
Like we have to do A* b = new A();
Also, where will a
and b
be stored in memory? Stack or heap?
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
In C++, an object is created from a class. We have already created the class named MyClass , so now we can use this to create objects. To create an object of MyClass , specify the class name, followed by the object name.
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.
To use the data and access functions defined in the class, you need to create objects.
In the first case, if a
is not a global variable, then it will be put on the stack, while b
will be put on the heap.
And in the first case, only the constructor is called. new
is never called except if you do it explicitly as in the second case.
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