Is possible to get object through dynamic_cast using multiple-inheritance ? I prefer to skip compositional trick due to designing issue I have. Thanks,
#include <stdio.h>
namespace
{
template <typename T>
class Beta
{
protected:
Beta() { printf("Beta\n"); }
public:
virtual ~Beta() { printf("~Beta\n"); }
virtual void Run() = 0;
};
class Alpha
{
protected:
Alpha() { printf("Alpha\n"); }
public:
virtual ~Alpha() { printf("~Alpha\n"); }
virtual void Check() = 0;
template <typename T>
Beta<T>* GetBeta()
{
Beta<T>* b = dynamic_cast< Beta<T>* >(this);
if(b == NULL) printf("NULL !!\n");
return b;
}
};
template <typename T>
class Theta : public Alpha, Beta<T>
{
public:
void Run()
{
printf("Run !\n");
}
void Check()
{
printf("Check !\n");
}
};
}
int main(int argc, const char* argv[])
{
Alpha* alpha = new Theta<int>();
Beta<int>* beta = alpha->GetBeta<int>();
alpha->Check();
if(beta) beta->Run();
delete alpha;
return 0;
}
The result from above code is
Alpha Beta NULL !! Check ! ~Beta ~Alpha
While typeid + static_cast is faster than dynamic_cast , not having to switch on the runtime type of the object is faster than any of them. Save this answer.
Yes, dynamic_cast is a code smell, but so is adding functions that try to make it look like you have a good polymorphic interface but are actually equal to a dynamic_cast i.e. stuff like can_put_on_board .
dynamic_cast runs at about 14.4953 nanoseconds. Checking a virtual method and static_cast ing runs at about twice the speed, 6.55936 nanoseconds.
For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b' (of type `class B*') to type `class D*' (source type is not polymorphic) ” because there is no virtual function in the base class B.
Well, if I replace:
public Alpha, Beta<T>
with:
public Alpha, public Beta<T>
Things will work. There is always a devil in the details...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With