Click here to Skip to main content
15,893,266 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
class A
{
    int m_aptr;
public:
    A(int p):m_aptr(p){}  //constructoe
    void setvalue(int v){m_aptr=v;}
    int getvalue(){return m_aptr;}
    A( const A  &a)  //copy constructor
    {
        *this=a;
        //m_aptr=a.m_aptr;
    }
    A operator=(const  A &a) //overloading '=' operator
    {
        m_aptr=a.m_aptr;
        return *this;
    }
};




int main()
{
    A a1(10);
    A a2(a1);
    cout <<"a2= "<<a2.getvalue()<<", a1= "<<a1.getvalue();

}
Posted
Updated 3-Sep-15 0:53am
v2
Comments
Afzaal Ahmad Zeeshan 3-Sep-15 6:54am    
Error?
the_beginner 3-Sep-15 6:57am    
No error , it just show stop working, also problem is due to
*this=a in copy-constructor, if I replace that line with line under it (which is commented out), program runs successfully

1 solution

The assignment operator must return a reference. So it must be:
A& operator=(const A &a) //overloading '=' operator
{
    m_aptr=a.m_aptr;
    return *this;
}
 
Share this answer
 
Comments
the_beginner 3-Sep-15 8:56am    
thanks it worked, but i am not using '=' in main code than how its affecting, also if same code is ran with

A( const A &a) //copy constructor
{
m_aptr=a.m_aptr;
}

it wrks fine how? , it would be great if u can answer.
Jochen Arndt 3-Sep-15 9:06am    
You use the copy constructor in your main code here:
A a2(a1);
And the copy constructor uses the assignment operator here:
*this = a;

Only if you replace the above by copying the member varaiable, the assignment operator is not used.
Sergey Alexandrovich Kryukov 3-Sep-15 9:31am    
5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900