JensB
JensB

Reputation: 939

Is there a way to make sure inherited member is not accessible in derived classes, while still keeping the benefits of public inheritance?

If I have a class that holds a protected member that derived classes will inherit:

class Base1
{
protected:
    int baseMember_;
};

class Base2 : public Base1
{
public:
    void printBaseMember
    {
        std::cout << baseMember_ << std::endl;
    }
};

How can I make sure that baseMember_ will be inaccessable in classes that derive from Base2?

The obvious solution would be to simply make the inheritance private: class Base2 : private Base1, but this doesn't work in my case. The reason is that private inheritance removes the is-a relationship between Base2 and Base1, which I need because I need to assign objects of typeBase1* to type Base2* in several places in my code.

Is there a way to make sure that derived classes will not have access to a protected member, while still using public inheritance?

Upvotes: 2

Views: 243

Answers (2)

Andrey Semashev
Andrey Semashev

Reputation: 10624

Is there a way to make sure that derived classes will not have access to a protected member, while still using public inheritance?

You can change the access mode of an inherited member by a using declaration:

class Base1
{
protected:
    int baseMember_;
};

class Base2 : public Base1
{
public:
    void printBaseMember()
    {
        std::cout << baseMember_ << std::endl;
    }

private:
    using Base1::baseMember_; // baseMember_ is private in the context
                              // of Base2; its derived classes cannot access it
};

You can also change the access mode in other ways, e.g. from protected to public. Here is an example on godbolt.org.

Note, however, that the classes that derive from Base2 can still access Base1::baseMember_ through this name. This will bypass the access check in Base2. They will not be able to access it through the unqualified name of baseMember_. You might want to use private inheritance of Base2 from Base1 and using-declare all public members of Base1 in Base2 to mitigate this.

Upvotes: 4

eerorika
eerorika

Reputation: 238401

How can I make sure that baseMember_ will be inaccessable in classes that derive from Base2?

By declaring the member private. You can declare Base2 to be a friend of Base1 so that it still has access.

Upvotes: 1

Related Questions