Hi All ,
In below code i am getting error while assigning one object with other and result is clear as both objects are different types.
it is expected that RHS object should belong to same class. How to resolve this issue.

error: no match for operator= in obj1 = obj2;

error: candidates are: const b& b::operator=(const b&)

#include <iostream>
using namespace std;

class a
{
int a1 ,b;
public:
a(int x=0,int y=0):a1(x),b(y){}
void fun1() {cout<<a1;cout<<b;}
};

class b
{
private:
a *p;
public:

b (int x=0, int y=0)
{
p= new a(x,y);
}
b ( const b &obj)
{
p = new a (*obj.p);
}

const b& operator=(const b &obj)
{
if(this !=&obj)
{
delete p;
p=new a(*obj.p);

}
return obj;
}
void fun2(){p->fun1();}
~b () { delete p;}

};
int main()
{
b obj1(10,20);
a obj2(20,30);
obj1=obj2;//error 
//obj1.fun2();
//b obj2(obj1);
//obj1.fun2();
return 1;
}

Recommended Answers

All 6 Replies

You can add an assignment operator in class b that takes a reference to an a object:

const b& operator=( const a& anA )
{
    if (&a != p)
    {
        delete p;
        p = new a(anA);
    }
    return *this;
}

Also, your b class copy constructor should return a reference to *this instead of obj.

Line 49: Why are you returning 1 instead of 0?

Dear rubberman, Thanks for your response. i tried to implement same way but i am getting compilation error for condition if (&a != p).

assign.cpp:29: error: expected primary-expression before â!=â token

apart from this if i want to assign a class object to b class object then one more version of assignment operator needs to be implemented (obj2=ob1) scenario which i don't want.

it should be if (&anA != p). Sorry, my bad. Dagnabbit keyboard! :-)

Another option,and possibly less confusing than trying to assign to an object of a different type, would be to use a constructor instead:

b(a& other)
{
    p = new a(other);
}

obj1 = b(obj2);

Thanks rubberman. for obj2=ob1 case i need to overload assignment operator in class a.

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.