0

Is it correct to call a virtual function of a base class implemented in the derived class in a non-virtual function of the base class. Something like

class A
{
 virtual void func1() = 0;

 void func2()
 {
   func1();
 }
};

class B : public A
{
 virtual void func1()
 {
   //do something here;
 }
};

int main()
{
 A* obj = new B;
 obj->func2();
 return 0;
}

4 Answers 4

2

Yes, this will work. Did you try it yourself?

1
  • 2
    +1. Of course sometimes "try it" leads to things like "y = x++ + x++" - which does "work", but doesn't "work right every time". So just because something works, doesn't mean it's acceptable or even right. Mar 13, 2013 at 17:37
2

Not only is it a well known and working way to solve things, but if the func2 is inlined, it probably means that there is no extra overhead compared to doing a direct call to the inside function. Obviously, sometimes the whole purpose is to do some things inside func1 and then call func2 in the middle or at the end, but in cases where that extra work is minimal, the "extra function layer" probably disappears completely.

1

Yes. This technique is used when you need virtual function behavior for operator implementations: you define your operator in terms of a virtual (or abstract) function and let specializations to decide how that function is implemented.

example:

class base
{
// yada yada yada
    base& operator=(const base& other) { return assign(other); }
protected:
    virtual base& assign(const base& other) = 0; // specializations will decide
                                                 //  what assignment means
};

Edit: another use for the technique is to allow specializations of your class to control only parts of a more complex operation:

class database
{
public:
    void execute(const std::string& query)
    {
        begin_transaction(); // in practice, this should be RAII
        connection_.execute(query);
        end_transaction();
    }
protected:
    virtual void begin_transaction() = 0;
    virtual void end_transaction() = 0;
private:
    whatever &connection_;
};

In the database specializations, a hypothetical mysql_database::begin_transaction would have a different implementation than sqlite_database::begin_transaction.

1

Yes that's fine. This allows you to provide common flow in the base class, the details of which are specialized in its children.

See template method.

1
  • ok, thanks :) . I was trying something complicated within func1 which was giving me linker errors which i thought was due to implementation fault :)
    – sn710
    Mar 13, 2013 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.