class B;
class A{
B *b;
public:
void operator= (B *b){
this->b = b;
}
};
B *b = new B()
A *a = new A();
a = b;
I get a “cannot convert B* to A*” error.
Is there a way around this?
Now, if there is a way, and if I use something like:
a = NULL;
Which operator “=” would be used?
Your
operator=provides assignment from aB*to anA. Your code does not provide a conversion from aB*to aA*(as the error message shows). As such,a=NULLwill not use the assignment operator you provided, sinceais a pointer, not anA. Your code allows assignment from aB*to anA, likeA a= new B();.If you meant to be using actual objects instead of pointers, remove all the
*from your code:If you wanted to be using pointers, the only “useful” way to assign a
B*to anA*is if aBobject derives fromA. That appears to not be what you’re doing, so assigning aB*to anA*would make no sense in your code.