Search code examples
c++operator-overloadingassignment-operator

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?


Solution

  • 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.