0

A very basic question. If you have a base class with virtual method and an extended class with the overloading of that virtual method. For example:

class Base
{
  protected:
    virtual void method(int a_1,int a_2);
};

class Extended:public Base
{
  protected:
     void method(int a_1,int a_2)
};

What is a good practice to avoid someone change Base method definition without change the method in the exteded class? Is there any solution for detect this in compilation time ? BTW I am using VS2005, then I can't use C++11 or above.

Mauricio Ruiz
  • 322
  • 2
  • 10
  • 1
    maybe you are looking for this: https://stackoverflow.com/questions/18198314/what-is-the-override-keyword-in-c-used-for – 463035818_is_not_an_ai Nov 26 '19 at 19:08
  • Thank you @formerlyknownas_463035818, but I am using VS2005. I press my boss to buy VS2015. – Mauricio Ruiz Nov 26 '19 at 19:13
  • the only alternative I am aware of is making the method pure virtual in `Base` but this is not always applicable – 463035818_is_not_an_ai Nov 26 '19 at 19:18
  • btw in case you cannot use c++11 you should tag c++03, I was going to do it, but as there is already an answer I was relcutant – 463035818_is_not_an_ai Nov 26 '19 at 19:19
  • 1
    This doesn't help if you're only implementing the Base class, but as the implementer of the Extended class it's a good idea to ensure that your method's implementation calls up to the base class implementation (i.e. it calls `Base::method(a_1,a_2);`); that way if the base-class method's signature changes in a way that is incompatible with the subclass's method-signature, you will get a compile-time error. – Jeremy Friesner Nov 26 '19 at 19:20
  • "avoid someone change Base method definition" generally, this shouldn't matter if someone changes the base method definition. You're overriding it anyway. Perhaps could you give an example implementation of what you mean and what behavior you're trying to avoid? –  Nov 26 '19 at 19:56

1 Answers1

3

If your compiler supports C++11 you can use override.

In your case, if you add override to the method in Extended class, compiler will rise an error if someone changes the method definition in Base class without changing it in Extended.

class Extended:public Base
{
  protected:
     void method(int a_1,int a_2) override;
};
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
NewMe
  • 162
  • 4