I was asked to make a slight change on an old project build with Visual Studio 2013 VC++. So, I installed VS2013, made the change, compiled it but its behavior has changed on a code that I didn't touch.
After the update, a virtual method that was calling the method on the derived class is calling the method on the base class now.
I'm not a C++ expert but I can see that this a bad practice. All I want to know if there was a breaking change in C++ around this so I can explain to the person who asked me to update this project.
class BaseItem
{
public:
virtual void SetValue(int first, int* second = nullptr)
{
};
}
class DerivedItem : public BaseItem
{
public:
virtual void SetValue(int first)
{
};
}
BaseItem* item = new DerivedItem();
// Before: SetValue on the DerivedItem was called.
// After: SetValue on the BaseItem is called.
item->SetValue(5, nullptr);
and if I edit the DerivedItem like this:
class DerivedItem : public BaseItem
{
public:
virtual void SetValue(int first, int* second = nullptr)
{
};
}
the SetValue
on the DerivedItem is called again.
DerivedItem::SetValue
with theoverride
specifier, and only one of your examples will compile.DerivedItem::SetValue(int first)
is a different function than theBaseItem::SetValue()
because they have different parameter lists. To overload functions, they must have the same signature, i.e. quantity of parameters and return type. A default parameter counts as a parameter (the compiler sets the value if the parameter is not specified).int second = nullptr
, missing semicolons are the signs of a not real simplified code.SetValue
inDerivedItem
does not overrideSetValue
inBaseItem
. Never did. What the question describes would be a compiler bug.nullptr
is not a valid initializer for anint