Aslan986
Aslan986

Reputation: 10324

Use the base-class virtual method

Starting from this code:

class Base{
public:
    virtual void foo(){....}
};
class Derived{
public:
    void foo(){....}
};

If d is a Derived object, can I in some way invoke the foo method defined in the Base class for this object?

Edit: i mean from the outside, such that d.foo() binds to Base::foo()

Upvotes: 1

Views: 118

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490218

To call it from outside code, you can still explicitly qualify the name in the call:

#include <iostream>
#include <vector>

struct base { 
    virtual void do_something() { std::cout << "Base::do_something();\n"; }
};

struct derived : public base { 
    virtual void do_something() { std::cout << "derived::do_something();\n"; }
};

int main() {

    derived d;

    d.base::do_something();
    return 0;
}

If you're using a pointer to the object, you'd change that to d->base::do_something();.

Upvotes: 3

Just qualify the call (Assuming that Derived actually inherits from Base, which in your code it doesn't):

Derived d;
d.Base::foo();

Now, while this is doable, it is also quite questionable. If the method is virtual, it is meant to be overridden and users should not call a particular override, but the final-overrider, or else they risk breaking class invariants all the way through.

Consider that the implementation of Derived::foo did some extra work needed to hold some invariant, if users call Base::foo that extra work would not be done and the invariant is broken, leaving the object in an invalid state.

Upvotes: 6

pmr
pmr

Reputation: 59811

Specify it explicitly in the call.

#include <iostream>

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

    }
};

int main()
{
  Derived d;
  d.Base::foo();
  return 0;
}

Upvotes: 6

Related Questions