umps
umps

Reputation: 1199

How to call a base class's virtual function that is an input argument to a function

using C++, I have

struct Base {
    virtual void stuff(/*base stuff*/);
};

struct Derived : public Base {
    void stuff(/*derived stuff*/); 
};

void function1(Derived& obj){
   obj.stuff(); 
}

In this scenario, function1 will use Derived's do() function. What if in function1, I want to call the Base class's do() function instead ? Will it work if I call function1 as function1(dynamic_cast<Base*>(derived_obj_ptr))?

Upvotes: 0

Views: 102

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272677

After correcting the multitude of errors in your code, this is indeed achievable:

#include <iostream>

class Base {
public:
    virtual void foo() { std::cout << "Base\n"; }
};

class Derived : public Base {
public:
    void foo() { std::cout << "Derived\n"; }
};

void function1(Derived *p) {
   p->Base::foo();  // <<<<< Here is the magic >>>>>
}

int main() {
    Derived d;
    function1(&d);
}

Output:

Base

(see http://ideone.com/FKFj8)

Upvotes: 7

Related Questions