Home > Backend Development > C++ > Why is Explicit Method Invocation Required for Overloaded Methods in Derived Classes?

Why is Explicit Method Invocation Required for Overloaded Methods in Derived Classes?

DDD
Release: 2024-11-02 12:50:02
Original
1055 people have browsed it

Why is Explicit Method Invocation Required for Overloaded Methods in Derived Classes?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template