class MyClass
{
private:
int color;
string name;
public:
MyClass(int co, string n) :
name(n), color(co)
{
cout << "MyClass created" << endl;
}
~MyClass()
{
cout << "MyClass is deleted" << endl;
}
string getName()
{
return this->name;
}
};
MyClass func()
{
MyClass c(0, "test");
return c;
}
int main()
{
MyClass cls = func();
cout << cls.getName() << endl;
}
And the output:
MyClass created
test
MyClass is deleted
Hello, I know that in C it's impossible to get an address of local variable from function calls ( i.e - it's impossible to initaialize on the stack an array of int by calling another function and returns it) .
I noticed that in C++ something is different;
I created an instance of some object without use the operator new
, outside the main function, then returns it to the main function and it's like I initizalized in the main. May someone can explain why the address of object's instance didn't free after the function which created it terminated?
(I expected that MyClass instance deleted when func terminated - No "test" on the output)
thanking you in advance