C Overload Resolution: Explicit Method Selection Required
In C , overload resolution occurs based on the argument types and the scopes in which a method is declared. To ensure accurate method selection, certain scenarios require explicit method invocation.
Consider the following example:
<code class="cpp">class A { public: int DoSomething() { return 0; } }; class B : public A { public: int DoSomething(int x) { return 1; } }; int main() { B* b = new B(); b->A::DoSomething(); // Why this? // b->DoSomething(); // Why not this? (Compiler error) delete b; return 0; }</code>
Why is the statement b->A::DoSomething(); necessary?
Understanding Overload Resolution:
In this case, the compiler considers the scope of the method when performing overload resolution. By default, it only searches within the current class's scope for a method match. In class B, the compiler finds DoSomething(int) within the current scope, which accepts a single int argument.
Explicit Invocation Required:
However, the parent class A also declares a version of DoSomething() that takes no arguments. To access this method in the derived class B, it must be explicitly invoked using the class scope operator (A::).
The statement b->DoSomething(); would fail to compile because the compiler cannot find a method named DoSomething() without arguments within the scope of class B. It incorrectly assumes that DoSomething(int) is the intended method.
Solutions:
To address this issue, one solution is to introduce the using declaration in class B. This pulls the DoSomething() method from the parent class into the derived class's scope:
<code class="cpp">class B : public A { public: using A::DoSomething; // … };</code>
With this modification, overload resolution can now correctly identify the desired DoSomething() method, eliminating the need for explicit invocation using b->A::DoSomething();.
The above is the detailed content of Why is Explicit Method Invocation Required for Overloaded Methods in Derived Classes?. For more information, please follow other related articles on the PHP Chinese website!