Student000
Student000

Reputation: 3

c++ How to call child method in abstract parent class?

I have a problem with my code.

class A{
    virtual foo()=0;
}

class B: public A {
    foo();
    foo2();
    operator X(A * a) {a->foo2()}   //doesn't work
}

class C: public A {
    foo();
    foo2();
    operator X(A * a) {a->foo2()} //doesn't work.
}

So I have a virtual class, and 2 classes that inherit from it. And I have to define an operator X that acts on an A object, no matter if it is B or C (since it can't be A because A is abstract). The problem is that the operator calls foo2(), which I'm not allowed to write in class A. What should I do?

Thanks a lot for helping me. This is my first post.

Upvotes: 0

Views: 1048

Answers (1)

The right answer is to declare foo2 pure virtual in A. However you have been told you are not allowed to do this. Boo :-(

Your only remaining option is to use dynamic_cast.

void do_foo2(A* a)
{
    if (B* b = dynamic_cast<B*>(b))
        return b->foo2();
    C& c = dynamic_cast<C&>(*a);  // Will throw if a is not B or C.
    return c.foo2();
}

Then

void B::operator X(A* a)
{
    do_foo2(a);
}

Note: This all assumes you are supposed to make B::operator X work with both B and C.

Upvotes: 1

Related Questions