C++ virtual function from privately inherited class, promoted to public in derived class declaration

322 views Asked by At

I have the following scheme:

class Interface
{
    virtual ~Interface() { }
    virtual void foo() const = 0;
    virtual void bar() const = 0;
}

//Interface is derived privately mostly for preventing upcast outside
class Derived : private Interface
{
public:
    void foo() const;
private:
    void bar() const;
}

It does not compile : foo is private. Is there any way to make it public without adding a dummy public function?

3

There are 3 answers

0
Lightness Races in Orbit On

No, there is not.

Furthermore, even a dummy public function would require that foo in the base were protected, not private.

I would revisit your design. If the function is intended to be public, then why is it not public?

0
opetroch On

It is not allowed to change the accessibility of an inherited member. If it was allowed, you would be able to derive from a class and make its private or protected members public, breaking the encapsulation.

0
T.C. On

It is perfectly valid, as far as the language is concerned, for a public member function in a derived class to override a private member function in the base class. Whether doing so is a good idea is a different question. And it certainly makes little sense for an abstract base class to have no public member functions.

The problem with your code is that Interface has a private destructor, making it impossible for derived classes to destroy their base class subobjects. ~Interface() should be either protected or public.