Reputation: 47
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
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