c++static-cast

static_cast an interface to derived class


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?


Solution

  • 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();
    }
    

    If the members of vector are always of derived type, you might also consider using a vector<cDerived*> instead. This would avoid the cast altogether:

    std::vector<D*> v;
    v.push_back(new D());
    R *r = v[0]->getR();