Update: This issue is caused by bad memory usage, see solution at the bottom.
Here’s some semi-pseudo code:
class ClassA { public: virtual void VirtualFunction(); void SomeFunction(); } class ClassB : public ClassA { public: void VirtualFunction(); } void ClassA::VirtualFunction() { // Intentionally empty (code smell?). } void ClassA::SomeFunction() { VirtualFunction(); } void ClassB::VirtualFunction() { // I'd like this to be called from ClassA::SomeFunction() std::cout << "Hello world!" << endl; }
The C# equivalent is as follows: Removed C# example, as it’s not relevant to the actual problem.
Why isn’t the ClassB::VirtualFunction function being called when called from ClassA::SomeFunction? Instead ClassA::VirtualFunction is being called…
When I force implementation of the virtual function ClassA::VirtualFunction, like so:
class ClassA { public: virtual void VirtualFunction() = 0; void SomeFunction(); } class ClassB : public ClassA { public: void VirtualFunction(); } void ClassA::SomeFunction() { VirtualFunction(); } void ClassB::VirtualFunction() { // I'd like this to be called from ClassA::SomeFunction() std::cout << "Hello world!" << endl; }
The following error occurs at runtime, despite the derrived function deffinately being declared and defined.
pure virtual method called terminate called without an active exception
Note: It seems like the error can be caused even by bad memory usage. See self-answer for details.
Update 1 – 4:
Comments removed (not releavnt).
If in the Base class you do not want to implement the function you must declare so:
And the compiler won’t allow you to instantiate the class:
As a side note, be careful not to call virtual functions from constructors or destructors as you might get unexpected results.