Posts Tagged override
Nice bug I had with virtual functions in C++
Yesterday I asked to take a look to one bug in our application. Some application feature which was always worked, stopped working. The guy who last touched this part of application, said it is not his fault, and and he didn’t done something that could affect this feature. After 9 hours investigation, I found the problem, and it was so interesting, so I decided to write about it.
Suppose, you have base class ‘BaseClass’, and it defines some virtual method ‘SomeMethod’. All classes derived from BaseClass override this method. For example
class BaseClass
{
public:
virtual void SomeMethod(int arg1, int arg2);
};
class A
{
public:
virtual void SomeMethod(int arg1, int arg2);
};
class B
{
public:
virtual void SomeMethod(int arg1, int arg2);
};
class C
{
public:
virtual void SomeMethod(int arg1, int arg2);
};
… and so on. About 10 classes in different places inside very large and complicate application. In some place in application you call these methods:
for(int i=0; i<10; i++)
{
BaseClass baseClass = (BaseClass ) someClass;
baseClass.SomeMethod(0,0);
}
In for loop above, we using polymorphism to call to right function for each someClass object. So far so good.
Now some guy, decided to add additional parameter to SomeMethod in base class. But he didn’t updated all derived classes, but some of them. The result was as following:
class BaseClass
{
public:
virtual void SomeMethod(int arg1, int arg2, int arg3);
};
class A
{
public:
virtual void SomeMethod(int arg1, int arg2);
};
class B
{
public:
virtual void SomeMethod(int arg1, int arg2, int arg3);
};
class C
{
public:
virtual void SomeMethod(int arg1, int arg2);
};
You see what wrong? Now the method signature in classes A and C differs from one in BaseClass, and therefore polymorphism not working anymore. All they do are declaring virtual functions of their own. So in loop above, when we cast class A to BaseClass, and calling to SomeMethod – actually we calling to method in the base class. This situation however, is not possible in C#: to override virtual functions we use keyword ‘override’, and in case base method signature will change, we will get error during compilation. By the way, even if base method and override method differs only by ‘const’ keyword – this is good enough to kill polymorphism.
Add comment December 28, 2007