Answer the question
In order to leave comments, you need to log in
How to recover a pointer to a non-first base class from an unknown derived class?
There are some classes A, B, C, D, E.
A, B, C of them are interfaces.
The inheritance hierarchy is as follows:
Classes D and E have two parents
{A, C} -> D, {B, C} -> E.
So. I have a function that is passed a pointer of type void*, but it is assumed that it points to an object of one of these classes. I need to correctly cast this void* pointer to a pointer to the C class. If I cast a void* that pointed to class D to a pointer to C and called one of the C methods, then this led to a crash, but if I cast to a pointer to class A and call its methods, then everything works fine.
Answer the question
In order to leave comments, you need to log in
#include <stdio.h>
class A
{
public:
virtual ~A()
{
}
};
class B
{
public:
virtual ~B()
{
}
};
class C
{
public:
virtual void dump() = 0;
virtual ~C()
{
}
};
class D: public A, public C
{
public:
virtual void dump()
{
printf("D: %p\n", this);
}
};
class E: public B, public C
{
public:
virtual void dump()
{
printf("E: %p\n", this);
}
};
void f(void *p)
{
C *pc1 = dynamic_cast<C*>((A*)p);
C *pc2 = dynamic_cast<C*>((B*)p);
C *pc3 = dynamic_cast<C*>((C*)p);
if (pc1)
pc1->dump();
else if (pc2)
pc2->dump();
else if (pc3)
pc3->dump();
}
int main()
{
D d;
E e;
printf("d: %p, e: %p\n", &d, &e);
A *pa = &d;
f(pa);
B *pb = &e;
f(pb);
C *pc1 = &d;
f(pc1);
C *pc2 = &e;
f(pc2);
D *pd = &d;
f(pd);
E *pe = &e;
f(pe);
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question