Reputation:
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?
Upvotes: 0
Views: 1879
Reputation: 3598
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.
Upvotes: -2
Reputation: 7466
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()
Upvotes: 1
Reputation: 76805
Well, first of all your code does not compile regardless of the call to Update
:
Update
member functions lack returns typesShape
inherits privately from Physics
and Graphics
, so Update
is inaccessible from main
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();
Upvotes: 9