Question

I've recently discovered the use of using to import a base class function into the namespace of a derived class (when it is being hidden). I was trying to use it to import a function from a base class as an implementation of the function in a derived class:

class A {
public:
  virtual void foo() = 0;
};

class B {
public:
  void foo() {
  }  
};

class C : public A, public B {
public:
  using B::foo;
};


int main()
{
  C c;
}

This won't compile as A::foo() is a pure virtual function in C. I was hoping that using B::foo; would make an implementation of foo(). Why isn't it so ?

Was it helpful?

Solution

You have two different functions: A::foo() and B::foo(). Although they have the same unqualified name, they are not related. B::foo() does not and cannot override A::foo() because B is not a subclass of A.

C inherits both functions from A and B. You use public inheritance for both base classes, so A::foo() and B::foo() are already visible in C (note that you need qualified name to invoke the functions to avoid ambiguity). So your using declaration has actually no effect.


A using declaration, when used inside a class, has to do with overloading, but it has nothing to do with overriding. These are very different concepts.

Overloading is about having different functions with the same name but different argument sets.

Overriding is about polymorphism, i.e. having varying implementations of a base-class method in derived classes.


A using declaration introduces a function name from a base class into a derived class, where that name would be hidden by another function with the same name but different arguments. For example:

class X
{  
 public:
  void func() {}
};

class Y : public X 
{  
 public:
  void func(int arg) {}
};

Y::func does not override X::func, since its arguments are different. Moreover, it also hides the name func from the base class, so it can be called only via qualified name, e.g.:

X x; 
x.func(); // ok

Y y; 
y.func(1); // ok, Y::func called 
y.func(); // error, base-class name func is hidden by local name 
y.X::func(); // ok, qualified name, X::func called 

In this case, a using declaration would introduce the name from the base class into the derived class, making func callable without name-qualifying:

class Y : public X 
{  
 public:
  using X::func; 
  void func(int arg) {}
};

// ...

Y y; 
y.func(); // ok, X::func called

OTHER TIPS

using in C++ has a different meaning and designates that you would like to be able to access a function/object in another namespace without typing the namespace name explicitly. It has nothing to do with overriding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top