I am trying to understand the memory used in a particular type of initialization. Here is an example for the question:
#include <iostream>
using namespace std;
class Example {
int n;
public:
Example(int number = 0)
{
n = number;
}
};
int main() {
Example *obj1 = new Example(1); //dynamic allocation - 1 instance is created and the object pointer points to the address
Example obj2(2); // automatic allocation - a single instance of the object is created with the given value
Example obj3 = Example(3); //automatic allocation - with copy constructor from an object initialized with a the class constructor
delete obj1; //de-allocating dynamically allocate memory
}
I am interested in knowing how obj3
is being instantiated. Does the usage of the equal to sign mean that we are using a copy constructor here? If so, is Example(3)
a separate instance (what is its scope)?
If they are separate instances, then it seems the initialization of obj2
more optimized, isn't it?
Edit: Fixed usage of incorrect terminology - static to automatic