Given this code:
class base {
public:
string foo() const; // Want this to be visible in 'derived' class.
}
class derived : public base {
public:
virtual int foo(int) const; // Causes base class foo() to be hidden.
}
How can I make base::foo() visible to derived without replicating it with a dummy method overloading that calls the base class? Does using
do the trick, if so, where does it go, is it like this?
class derived : public base {
public:
virtual int foo(int) const;
using base::foo;
}
Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.
A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.
Sorry for the short answer, but yes. It's exactly like this and does what you want:
class derived : public base {
public:
virtual int foo(int) const;
using base::foo;
};
Also note that you can access the base even without using
:
derived x;
string str = x.base::foo(); // works without using
The using directive will make selected methods from base visible to the scope of derived. But from a design point of view this is not desirable, since you're hiding names to the scope of derived while using a public interface. (Doing this with a private interface makes more sense)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With