L
L
LittleFatNinja2015-04-07 23:10:02
Programming
LittleFatNinja, 2015-04-07 23:10:02

C++ how to call a child method that is not defined in the ancestor?

I understand that in A there is no getSome () method, but it is in class B, and in foo () I just pass an instance of class B

class A {

}

class B : A {
  int getSome();
}

void foo(A& a) {
  a.getSome(); //error: class 'A' has no member 'getSome()'
}

int main() {
   B b();
   foo(b);
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
X
xibir, 2015-04-08
@LittleFatNinja

Add a virtual destructor to class A:
class A
{
public:
virtual ~A(){}
};
after that:

void foo(A& a)
{
   if (B* b = dynamic_cast<B*>(&a))
      b->getSome();
}

P
Pavel K, 2015-04-07
@PavelK

Through type casting?
Sorry, it won't work - catch the exception, because. there is no function implementation in class A.
I don't think so. We need to rethink the architecture.
Or transfer this method to another class, inherit A and B from it, and then type casting can be done.

A
Antony, 2015-04-08
@RiseOfDeath

In general, if your function foo accepts objects of type A, then it should not call functions that this object does not have. Those. Roughly speaking, class A defines an "interface" for all descendants, which all foo functions should pull.
Those. in your example should look something like this:
class A {
virtual int getSome()=0;
}
class B : A {
int getSome();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question