static_cast an interface to derived class
You can use static_cast
in your example.
But you must include both definitions of IInherit
and cDerived
for it to work. The compiler must see, that cDerived
inherits from IInherit
. Otherwise, it cannot decide that the static_cast
is indeed valid.
#include <vector>
struct R {};
struct B {};
struct D : public B {
R *getR() { return new R(); }
};
void f()
{
std::vector<B*> v;
v.push_back(new D());
D *d = static_cast<D*>(v[0]);
R *r = d->getR();
}
Related videos on Youtube
vaibhav kumar
Updated on June 04, 2022Comments
-
vaibhav kumar almost 2 years
I am trying to static_cast an interface object into object of derived class which inherits that interface. I am getting an error
'static_cast' : cannot convert from 'IInherit *' to 'cDerived *'
The derived class and interface are of the following format.
class cDerived: public IInherit { Repo* p_Repos; public: cDerived(Repo* pRepos) { p_Repos = pRepos; } Repo* GetRepo() { return p_Repos; } void doAction(ITok*& pTc) { ///some logic } } class IInherit { public: virtual ~IInherit() {} virtual void doAction(ITok*& pTc)=0; };
I have a
vector<IInherit*>
object accessible in the code through getInherit() method such that the type of getInherit()[0] is cDerived* I am performing static cast using the expression:Repo* pRep= static_cast<cDerived*>(getInherit()[0])->GetRepo();
I am not sure if it is possible to static_cast as interface object. Is there any other way that I would be able to perform this cast?
-
Lily Ballard about 11 yearsWhat compiler are you using? This works for me.
-
JoergB about 11 yearsCan you provide a complete example showing the error and the full error message?
-
Pete Becker about 11 yearsAre the definitions of
IInherit
andcDerived
both visible at the point where the error occurs? -
Saurav Seth about 11 yearsBy chance, is the real problem because you declared IInherit in your header file AFTER you declared cDerived as you did above? Or is that just how you cut&paste in the code above. There's a missing semi-colon after the delclaration of cDerived. I'm just wondering if compiler is erroring out on some other error before showing this error.
-
vaibhav kumar about 11 yearsNo I have forward declared the derived class, no issues with visibility
-
vaibhav kumar about 11 years@KevinBallard vc++ compiler
-
Peter Wood about 11 yearsWhy do you need to call
GetRepo()
?
-
-
François Moisan about 11 yearsThis is the answer. static_cast requires more than a forward declaration to ensure the cast is at least possible (though you could still be lying to the compiler).
-
Olaf Dietsche about 11 years@vaibhavkumar Visibility alone is not the issue, the compiler must see the definition, i.e. the inheritance. I updated my answer.