Question

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
Was it helpful?

Solution

Isnt it pretty obviously what happens here? In the line auto objA = objR; your objA variable is not deduced to a MyTest& but to a MyTest and becomes thus copy constructed from your obj (as objR is just a reference to it). You dont see any output as you havent implemented the copy constructer which is therefor automatically provided by the compiler for you.

If you now call

objR = MYtest("refmodified",1);

Your original object is modified (the assignment operator is called), but your copy (objA) is left untouched.

The other way round if you call

objA = MYtest("automodified",2);

Your copy is modified but your original object is left untouched.


To do what you want to achieve (objA being a reference to obj) you have to declare it like this:

auto& objA = objR;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top