I have some events like this
class Granpa // this would not be changed, as its in a dll and not written by me
{
public:
virtual void onLoad(){}
}
class Father :public Granpa // my modification on Granpa
{
public:
virtual void onLoad()
{
// do important stuff
}
}
class Child :public Father// client will derive Father
{
virtual void onLoad()
{
// Father::onLoad(); // i'm trying do this without client explicitly writing the call
// clients code
}
}
Is there a way to force calling onLoad without actually writing Father::onLoad()?
Hackish solutions are welcome :)
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
Access Overridden Function in C++ To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.
Calling virtual methods in constructor/destructor in C++You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.
If I understand correctly, you want it so that whenever the overriden function gets called, the base-class implementation must always get called first. In which case, you could investigate the template pattern. Something like:
class Base
{
public:
void foo() {
baseStuff();
derivedStuff();
}
protected:
virtual void derivedStuff() = 0;
private:
void baseStuff() { ... }
};
class Derived : public Base {
protected:
virtual void derivedStuff() {
// This will always get called after baseStuff()
...
}
};
As suggested above but applied to your case.
class Father :public Granpa // my modification on Granpa
{
public:
virtual void onLoad()
{
// do important stuff
onLoadHandler();
}
virtual void onLoadHandler()=0;
}
class Child :public Father// client will derive Father
{
virtual void onLoadHandler()
{
// clients code
}
}
However, nothing can prevent Child to override onLoad since c++ has no final keyword and Granpa onLoad is itself virtual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With