Home > Backend Development > C++ > How Can I Resolve Function Name Collision in C Inheritance?

How Can I Resolve Function Name Collision in C Inheritance?

Patricia Arquette
Release: 2024-12-21 16:02:10
Original
938 people have browsed it

How Can I Resolve Function Name Collision in C   Inheritance?

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);
    }
};
Copy after login

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template