Was trying to compare Auto variable with respect to Object reference variable and program got struck at main end. Its because of *ip
but am not able to understand Constructor/Destructor calls and why not new object created when auto objA = objR;
Code I wrote is below:
#include <iostream>
#include <string>
using namespace std;
typedef class auto_type_test
{
string name;
int age; int * ip;
public:
auto_type_test(const char* _name, int _age) : name(_name),age(_age){cout << "Constructor called"<<endl;ip= new int[2];}
auto_type_test() {}
~auto_type_test() {cout << "Destructor called"<<endl;delete []ip;}
friend ostream& operator <<(ostream& out, const auto_type_test& obj);
}MYtest;
ostream& operator <<(ostream& out, const MYtest& obj)
{
out << "Name:"<<obj.name<<" Age:"<<obj.age<<endl;
out << obj.ip[0] <<endl; // int pointer to test that auto variable not created
return out;
}
int main()
{
MYtest obj("OriginalObject",26);
MYtest& objR = obj;
auto objA = objR;
cout << obj << objR << objA << endl;
objR = MYtest("refmodified",1); //<line1>Commenting this and below line
//objA = MYtest("automodified",2); //<line2>alternatively
cout << obj << objR << objA << endl;
return 0;
}
When Line1 commented output:
Constructor called
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451
Constructor called
Destructor called
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451
Name:automodified Age:2
-17891602
Destructor called
When Line2 commented output:
Constructor called
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451
Name:OriginalObject Age:26
-842150451
Constructor called
Destructor called
Name:refmodified Age:1
-17891602
Name:refmodified Age:1
-17891602
Name:OriginalObject Age:26
-842150451
Destructor called
Destructor called