#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;
}

Recommended Answers

All 3 Replies

>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.

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.....

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.