4

I'm confused why the following code produces Woverloaded-virtual warning.

class TestVirtual
{
public:
    TestVirtual();
    virtual void TestMethod(int i);
};

class DerivedTestVirtual : public TestVirtual
{
public:
    void TestMethod();

};

Derived class has usual method TestMethod with no parameters - signature differs from similar virtual method of base class. Then why compiler cannot resolve this situation?

Roman Kazmin
  • 931
  • 6
  • 18
  • I use clang compiler – Roman Kazmin Sep 05 '17 at 17:04
  • Doing this by accident, intending to override the base function but not actually doing so, is a very common bug. That's why the warning exists. The new C++11 *override* specifier helps a lot to turn it from a warning into an error. Since it doesn't do much other than imperfectly hiding the base class method, consider simply giving it a different name. – Hans Passant Sep 05 '17 at 17:14

1 Answers1

5

The reason for the warning is that the no parameter version is hiding the int version from the base class.

DerivedTestVirtual tdv;
tdv.TestMethod(0); // This line will cause an error.

You can circumvent that by declaring you use all of the original overloads from the base, like so:

class DerivedTestVirtual : public TestVirtual
{
public:
    using TestVirtual::TestMethod;
    void TestMethod();
};

The warning is there to bring the issue to your attention. And it's also useful since such a mistake can happen when you try to override it, but accidentally end up overloading. Though nowadays you'd use the override specifier to catch that instead.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • You can add `using TestVirtual::TestMethod` within the definition of `DerivedTestVirtual` to expose the parameterized method in the derived class. – Jonesinator Sep 05 '17 at 17:05
  • @Jonesinator - Yes, but it's counter intuitive somewhat that you need to do so to begin with. – StoryTeller - Unslander Monica Sep 05 '17 at 17:05
  • It is clear how to fix this problem. But I cannot understand why it is happened with usual method. In case if DerivedTestVirtual::TestMethod is virtual all are clear..... I need more explanation for my case... – Roman Kazmin Sep 05 '17 at 17:09
  • 1
    @Mikola - It happens because that's how C++ is deigned. The fact the original is virtual doesn't change the behavior of overloading a derived member. – StoryTeller - Unslander Monica Sep 05 '17 at 17:10
  • 1
    @Mikola - If it's rationale you are after, read the answer to [this question](https://stackoverflow.com/questions/1628768/why-does-an-overridden-function-in-the-derived-class-hide-other-overloads-of-the). – StoryTeller - Unslander Monica Sep 05 '17 at 17:13