domlao
domlao

Reputation: 16029

Cast from Abstract Parent Class to Child Class

I have this code,

class IFoo
{
 public:
   IFoo(){}
   virtual ~IFoo(){}
   virtual void fooFunc() = 0;
};

class Foo : public IFoo
{
 public:
    Foo(){}
    virtual ~Foo(){}
    virtual void fooFunc(){/*impl*/}
};

class Poop : public IFoo
{
 public:
    Poop(){}
    virtual ~Poop(){}
    virtual void fooFunc(){/*impl*/}
};

class Bar
{
 public:
    Bar(){}
    ~Bar(){}
    void setFoo(Foo* foo){/*impl*/}
};

//in main
Poop* poop = new Poop;
Bar bar;
bar.setFoo(poop);

delete poop;

Compiling this code gives me an error message about invalid conversion. What kind of casting should I use for this?

Please advise. Many thanks!

Upvotes: 1

Views: 90

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598448

Poop does not derive from Foo, so you cannot pass a Poop* where a Foo* is expected, and vice versa. Poop and Foo both derive from IFoo so you need to instead change setFoo() to accept an IFoo* instead of a Foo*:

void setFoo(IFoo* foo){/*impl*/}

Upvotes: 1

Related Questions