How do I cast to an abstract class and call a function on it?

Hi,

In my project I have four classes - A,B,C and D.

C is an interface that A and B implement, with one pure virtual function.
https://speedtest.vet/
In class D, I am trying to cast to type C in order to call the pure virtual function without having to know whether it is A or B, however it isn't wanting to let me do this. Is there an easy way to do this?
https://showbox.tools/
I could make it a normal virtual function but I want to force any class that inherits from this to implement the function also.

Here is the line it is complaining about:

cImplementsBackButton_Interface* parent = dynamic_cast<cImplementsBackButton_Interface>(GetParent());

Thanks in advance.
Last edited on
There is a type error in the conversion, although it's not possible to be certain of the root cause because you didn't post enough code to reproduce the problem. Nor did you post the verbatim error message the compiler produced: a vague "compiler complains" is not useful for problem solving.

You should post the shortest program you can find that still exhibits the problem.

One possible fix is as follows
cImplementsBackButton_Interface& parent = static_cast<cImplementsBackButton_Interface&>(GetParent());
It is impossible to say whether this will actually resolve the issue without more information. For example, this is unsuitable if GetParent returns a pointer type.

In class D, I am trying to cast to type C in order to call the pure virtual function without having to know whether it is A or B, however it isn't wanting to let me do this.

You didn't mention which type is being converted to type C?

If it is a class type derived from C, consider this program
1
2
3
4
5
6
7
8
9
10
11
#include <cstdio>

struct C { virtual void f() const = 0; };
struct A: C { void f() const override { std::puts("A::f()\n"); } };
struct B: C { void f() const override { std::puts("B::f()\n"); } };

int main()
{
  B b; 
  b.f();
}

There is no reason to convert b to the type of its base class.
Last edited on
Topic archived. No new replies allowed.