views:

93

answers:

2

Consider the following code:


class Base
{
    void f() { }
};

class Derived: public Base
{
public:

};

What can you change in the derived class, such that you can perform the following:


Derived d;
d.f();

If the member is declared as public in the base class, adding a using declaration for Base::f in the derived class public section would've fix the problem. But if it is declared as private in the base class, this doesn't seem to work.

+1  A: 

You cannot access a private member from the derived class. What you can do is make it protected, and use a using declaration:

class Base
{
protected:
    void f() { }
};

class Derived: public Base
{
public:
    using Base::f;
};
Thomas
Yes, I've tried and this works.
jasonline
+4  A: 

This is not possible. A using declaration can't name a private base class member. Not even if there are other overloaded functions with the same name that aren't private.

The only way could be to make the derived class a friend:

class Derived;

class Base
{
    void f() { }
    friend class Derived;
};

class Derived: public Base
{
public:
    using Base::f;
};

Since you make the names public in the derived class anyway so derived classes of Derived will be able to access them, you could make them protected in the base-class too and omit the friend declaration.

Johannes Schaub - litb
I'd add he should think hard about why he wants do to this ;p
Joseph Garvin
@Joseph: I just remember this being asked in an interview, and the only thing allowed was to modify the derived class. I thought being a private/public member in the base class doesn't matter. But I guess it's not possible if the member is private.
jasonline