I am trying to have a non-virtual base class method call a derived method that overrides one of the base class's virtual methods. For the life of me, I can't get it to work. See the code below:
public ref class BaseClass
{
virtual void OverriddenMethod(){}
void Run()
{
// Do some initial work here.
// Call the derived class's version of OverridenMethod to do final work:
OverriddenMethod();
}
};
public ref class DerivedClass : public BaseClass
{
virtual void OverriddenMethod() override
{
// Do some final work here.
}
};
int main()
{
DerivedClass^ DC = gcnew DerivedClass();
DC->Run();
}
Using the code above, the base class's OverriddenMethod() gets called instead of the derived class's OverriddenMethod(), which isn't what I want. I was under the impression that, when using polymorphism, a call to a base class method that is overridden should instead call the overriding method of the derived class.
I have also tried using abstract:
public ref class BaseClass abstract
{
virtual void OverriddenMethod() abstract;
void Run()
{
// Do some initial work here.
// Call the derived class's version of OverridenMethod to do final work:
OverriddenMethod();
}
};
public ref class DerivedClass : public BaseClass
{
void OverriddenMethod()
{
// Do some final work here.
}
};
int main()
{
DerivedClass^ DC = gcnew DerivedClass();
DC->Run();
}
But this gives a C3278 compiler error (direct call of interface method 'interface method' will fail at runtime) when OverriddenMethod is called inside of the BaseClass::Run() definition.
override
regardless in this particular case. Also note that you need to set access modifiers so that the dirived class can override the base class – Mgetz