Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expose hidden overloading from base class?

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;
}
like image 959
WilliamKF Avatar asked Aug 10 '11 13:08

WilliamKF


People also ask

Can private members of base class become members of derived class?

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.

How do you access base class members in a derived class?

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.

How do you override a base class method in C++?

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.


2 Answers

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
like image 125
Yakov Galka Avatar answered Oct 20 '22 18:10

Yakov Galka


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)

like image 1
count0 Avatar answered Oct 20 '22 19:10

count0