Issue
see please the code:
#include <iostream>
using namespace std;
class A{
public:
A() = default;
virtual void foo() = 0;
bool foo(int x)
{
cout<<"A::foo(int x)\n";
return true;
}
bool func(int x)
{
cout<<"A::func(int x)\n";
return true;
}
};
class B: public A
{
public:
B() = default;
void foo()
{
cout<<"B::foo()\n";
}
};
int main()
{
B b;
b.func(0);
//b.foo(0); //it's not compiled
b.A::foo(0);
return 0;
}
It seems the parent's method should be called explicitly with the parent's prefix from the child object for any reason. b.foo(0)
is not compiled but if I add A:: prefix like b.A::foo(0)
it works.
Why is b.foo(0)
not compiled but b.func(0)
is?
Solution
It is called 'name hiding'.
You have a function called foo
without parameters in your subclass. The compiler will hide any other function with the same name from the superclass, unless you declare it with the using A::foo;
directive in the child class.
To my knowledge, this is done to avoid confusion of the function calls. All non-overloaded functions will be inherited automatically.
Your code should work, if you write it like this (untested):
class B: public A
{
public:
using A::foo;
B() = default;
void foo()
{
cout<<"B::foo()\n";
}
};
Please note that the using
syntax will move ALL functions called foo
into your subclass, regardless of their prototype.
For further information, see https://www.ibm.com/docs/en/zos/2.3.0?topic=scope-name-hiding-c-only or https://bastian.rieck.me/blog/posts/2016/name_hiding_cxx/
Answered By - Refugnic Eternium Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.