C++: Overlapping base class methods
When inheriting two base classes, what happens if both have a method with the same name and signature?
class Physics
{
public:
void Update开发者_运维百科() { std::cout << "Physics!" }
};
class Graphics
{
public:
void Update() { std::cout << "Graphics!" }
};
class Shape : Physics, Graphics
{
};
int main()
{
Shape shape;
shape.Update();
}
What will happen?
Well, first of all your code does not compile regardless of the call to Update
:
- The
Update
member functions lack returns types Shape
inherits privately fromPhysics
andGraphics
, soUpdate
is inaccessible frommain
Now, that being said, what happens when you attempt to call Update
is an ambiguity which will lead to a compilation error. This ambiguity may be lifted using :
shape.Physics::Update();
shape.Graphics::Update();
Found here https://gist.github.com/752273
$ g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:22: error: request for member ‘Update’ is ambiguous
test.cpp:12: error: candidates are: void Graphics::Update()
test.cpp:6: error: void Physics::Update()
In this case, it should call Physics::Update because you specified that first when you defined the inheritance. Actually, in this case it won't work because it's not visible to you because you didn't specify public inheritance, but if you did, you should get Physics::Update by default. The best thing for you to do is to resolve the any ambiguity by writing Shape::Update and having that call Physics::Update and/or Graphics::Update as necessary.
精彩评论