Could someone explain why not the copy-constructor is invoked??
Code:
class Test
{
public:
Test(int tal1, float tal2);
~Test();
Test(const Test &rhs);
Test operator+(const Test &arg2);
int getInttal() const;
float getFloattal() const;
private:
int _ital;
float _ftal;
};
Test::Test(int tal, float tal2):
_ital(tal), _ftal(tal2)
{
cout << "cstr called" << endl;
}
Test::Test(const Test &rhs):
_ital(rhs._ital), _ftal(rhs._ftal)
{
cout << "COPY" << endl;
}
Test::~Test()
{
cout << "decstr" << endl;
}
Test Test::operator+(const Test &arg2)
{
return Test(_ital + arg2._ital, _ftal + arg2._ftal);
}
int Test::getInttal() const
{
return _ital;
}
float Test::getFloattal() const
{
return _ftal;
}
int main()
{
Test numb1(10, 25.5f);
Test numb2(5, 40.5f);
//Copy contructor is not called
Test sum(numb1 + numb2);
return 0;
}
The overloaded+operator returns a temporary Test object and that object i passed as an argument to the copy-constructor. It seems that neither the constructor or the copy-consrcutor is invoked when the sum object is declared. When I run the program it seems that the constructor is invoked 3 times. And when a change the code to
Code:
int main()
{
Test numb1(10, 25.5f);
Test numb2(5, 40.5f);
numb1 + numb2;
return 0;
}
it proves that the operator+ is invoked and returns a temporary object (3:rd). Why isnīt the copyconstructor invoked in the statement
Code:
Test sum(numb1 + numb2);