TimeToEnjoy
TimeToEnjoy

Reputation: 47

Call no-virtual subclass method from a pointer base abstract class

I need to use a pointer of class A. But how can I call the class B method in this way? The method is not virtual, it owns at class B.

class A
{
private:
    string x;
public:
    virtual void J() = 0;
};

class B : public A
{
private:
    int y;
public:
    virtual void J(){
        cout << "J()";
    }
    void K(){
        cout << "K()";
    }
};

int main(){
    B b;
    A* a = &b;
    K(); //How can I call method K() with pointer a?
}

Upvotes: 0

Views: 49

Answers (1)

Jarod42
Jarod42

Reputation: 217145

With dynamic_cast, you may do

B b;
A* a = &b;
if (auto* bp = dynamic_cast<B*>(a)) {
     bp->K();
}

but you should probably rethink your design.

Upvotes: 4

Related Questions