Search code examples
c++inheritanceassignment-operator

Prevent call to base assignment operator in C++


I have these two classes in my library:

class Base {
    int _handler;
protected:
    Base() = default;

    Base& operator=(int h) {
        this->_handler = h;
        return *this;
    }
};

class Derived : public Base {
protected:
    Derived() = default;

    void initialize() {
        this->Base::operator=(12345); // internal stuff
    }
};

Derived class is available to be inherited by the user. He should do this:

class User_Class : public Derived {
    void foo() {
        this->initialize();
    }
};

But instead, he does this:

class User_Class : public Derived {
    void foo() {
        this->Base::operator=(999); // no, you broke it!
    }
};

How can I prevent the call to the Base assignment operator?


Solution

  • When I change the header to this

    class Derived : private Base
    

    the compiler immediately blocks the call to operator= with "cannot access inaccessible member declared in class 'Base'", however the code which calls initialize works normally, because that is accessible.

    However, you should also override operator= in Derived, and just have it check whether or not it has been initialized. Don't make the client class handle internal bookkeeping.