Function Collision in Derived Class
When defining a function with the same name but different signature in a base class and its derived class, a name lookup issue can arise.
Consider the following code:
class A { public: void foo(string s){}; }; class B : public A { public: int foo(int i){}; }; class C : public B { public: void bar() { string s; foo(s); } };
In this example, the compiler raises an error when trying to access the foo() function from the base class A within the bar() function of class C. It's because name lookup prioritizes finding the function in the most immediate class, in this case, B, and overlooks the overridden function in A.
To resolve this issue, the derived class B must explicitly declare the overridden function using the using directive:
class B : public A { public: int foo(int i){}; using A::foo; };
By using the using directive, B effectively re-introduces the foo() function from A into its own scope, making it visible to subsequent derived classes like C.
The above is the detailed content of How Can I Resolve Function Name Collision in C Inheritance?. For more information, please follow other related articles on the PHP Chinese website!