0
#include<iostream>
using namespace std;
class alpha{
private:
int data;
public:
alpha(){}
alpha(int a){data=a;}
void display(){
cout<<data;
}
alpha operator =(alpha& a){
cout<<data;
data=a.data;
cout<<"\n assignement operator invoked";
return alpha(data); // is temporary object created is returned to a2 object ?//why it can't be returned by reference?what is the difference b/w assignement and initiallizing

}
};

int main(){
alpha a1(123);
alpha a2(10);
a2=a1;
cout<<"\na2";a2.display();
a1.display();
return 0;
}

Edited by Dani: Fixed formatting

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Narue
0

>is temporary object created is returned to a2 object ?
Conceptually, yes. In practice compilers can often optimize away return value temporaries.

>why it can't be returned by reference?
Well, in this case it can't because then you would be returning a reference to a local object, which is immediately destroyed upon return. It would be a reference to a destroyed object. However, your implementation of the assignment operator is not idiomatic. This is more typical:

alpha& operator=(const alpha& a)
{
    data = a.data;
    return *this;
}

>what is the difference b/w assignement and initiallizing
Put simply, initialization works on a new object and assignment works on existing objects.

0

Narue-

alpha operator =(alpha& a){
cout<<data;
data=a.data;
cout<<"\n assignement operator invoked";
return alpha(data);

now is this returning alpha to a2. means now a2 is returned object or a2 object is different and returned object is different.....

0

>means now a2 is returned object or a2 object is different and returned object is different.....
The returned object (which has nothing to do with a2) is ignored because you don't assign the result of the assignment expression to anything in main. Regardless of your return value, the operator correctly performs the assignment with the data = a.data; statement.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.