Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Overloading assignment operator: "cannot convert `B*` to `A*`" error

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?

like image 606
nahpr Avatar asked Dec 06 '22 12:12

nahpr


2 Answers

You have assigned the pointer instead of the object. Simply replace the last instruction with: *a = b;

To answer the second question: NULL can be defined in more than one way in the compiler (as of the latest standard, either as the integral 0 or the literal nullptr). Pointers can also be cast to pointer of other types, but passing a void* to an overloaded function that takes an int* or a long* may make the compiler unable to resolve the function being called.

If however, you want to avoid NULL, simply make operator(B& b) instead. References are sure to be pointing at an object.

like image 103
E_net4 stands with Ukraine Avatar answered Dec 09 '22 15:12

E_net4 stands with Ukraine


Your operator= provides assignment from a B* to an A. Your code does not provide a conversion from a B* to a A* (as the error message shows). As such, a=NULL will not use the assignment operator you provided, since a is a pointer, not an A. Your code allows assignment from a B* to an A, like A a= new B();.

If you meant to be using actual objects instead of pointers, remove all the * from your code:

class B{};    
class A{    
    B b;
    public:
    void operator= (const B& b){ //pass non-primitives by const reference
        this->b = b;
    }
}; 

B b;
A a;
a = b;

If you wanted to be using pointers, the only "useful" way to assign a B* to an A* is if a B object derives from A. That appears to not be what you're doing, so assigning a B* to an A* would make no sense in your code.

like image 27
Mooing Duck Avatar answered Dec 09 '22 14:12

Mooing Duck