functionc++11usinginherited-constructors

Confusion about the necessity of "using" keyword with inheritance and constructors in C++11


I'm new to learning C++, and while exploring C++11 concepts, I came across the relationship between the "using" keyword and inheritance. My code consists of Base and derived Derived classes.The Base class has a member function named foo().In the Derived class, I utilize the "using" keyword to make the Base class's foo() function accessible.

class Base {
public:
void foo() { std::cout << "Base::foo()" << std::endl; }
};

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

int main() {
Derived obj;
obj.foo();  
return 0;
}

However, even without the "using" keyword(by commenting the using Base::foo; line), the program compiles and runs without errors.

I'm confused about whether the "using" keyword is mandatory here. Can you explain in which scenarios using the "using" keyword is crucial and what issues I might face if I omit it?

Thank you in advance for your answers!

I attempted to run the code by removing the "using" keyword, and the code executed smoothly.However, when I asked this to ChatGPT, it stated that the code would be incorrect without the "using" keyword and advised me to use it.


Solution

  • ChatGPT is wrong (again). You're right that it's unnecessary here. There's no ambiguity at all, Derived inherits only from Base. C++ however supports multiple inheritance, and in that case you might need to pick a specific foo.

    Also, Derived::foo is public like Base::foo, so there's no change there either.