1
votes

May be my question is wrong. I am new to C++. Is there any way call a base class member function using derived class object if that function is being overridden in derived class?

For example:

class A {
public:
    void add() { cout<<"A"; }
};

class B: public A {
public:
    void add() { cout<<"B"; } 
};

int main() {
    B bObj; 
    bObj.add(); // calls member function of class B
    return 0; 
}
2

2 Answers

1
votes

First of all, you aren't really overriding the add function, merely hiding the name, since A::add is not declared virtual.

To call A::add, just be explicit about it:

bObj.A::add();
0
votes

Typically, B::add() exists for a reason and you probably shouldn't be calling A::add() on a B. Which isn't to say you can't - you just have to turn it into an A first:

B bObj;
static_cast<A&>(b).add(); // calls A::add()

Or explicitly specify that it's A::add():

bObj.A::add();

From within B, you have to qualify the call:

class B: public A {
public:
    void add() { cout<<"B"; } 

    void test() {
        add();    // calls B::add
        A::add(); // calls A::add
    }
};