Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force calling base class virtual function

Tags:

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 :)

like image 906
mikbal Avatar asked Mar 15 '12 16:03

mikbal


People also ask

Can we call virtual function of base class?

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.

How do you call base class overridden in C++?

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.

Can we call virtual function in C++?

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”.


2 Answers

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()
        ...
    }
};
like image 172
Oliver Charlesworth Avatar answered Oct 05 '22 20:10

Oliver Charlesworth


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.

like image 27
dweeves Avatar answered Oct 05 '22 21:10

dweeves