Hi Guys,
In below code you can see that i am able to execute the functionality of class a , inside the class b
through composition and object of b can be used to call the methods declared inside the a class.
#include <iostream>
using namespace std;
class a
{
int a1;
public:
a( int _a1=0):a1(_a1)
{
}
void showname()
{
cout<<"class name a with value ="<<a1<<endl;
}
};
class b
{
public:
b(a* cobj) : cobj(cobj)
{
cout<<"object initialization\n";
}
void display()
{
cobj->showname();
}
~b ()
{
cout<<"deleted the object of a"<<endl;
delete cobj;
}
private:
a *cobj;
};
int main() {
a aobj(10);
b bobj(&aobj);
bobj.display();
}
Now same thing i want to achieve through assignment operator and for the same i have overloaded the assignment operator inside the class b but
i am getting compilation error after executing below code snippet :
error:
cannot convert 'a' to 'b' in assignment
bobj=aobj;
^
and due to this error it seems to be bobj->showname(); is not also functional as still content of aobj is not copied to bobj and it is still behaving
class b's object. I never been able to perform assignment between different kind of objects. Please suggest.
code snippet:
#include <iostream>
using namespace std;
class a
{
int a1;
public:
a( int _a1=0):a1(_a1)
{
}
void showname()
{
cout<<"class name a with value ="<<a1<<endl;
}
};
class b
{
public:
const b& operator=(const b& rhs);
private:
a *cobj;
};
const b& b::operator=(const b& rhs)
{
a *origobj=cobj;
cobj=new a (*rhs.cobj);
delete origobj;
return *this;
}
int main() {
a *aobj=new a;
b *bobj=new b;
bobj=aobj;
bobj->showname();
return 0;
}