samedi 25 juillet 2015

dynamic cast a reference and auto

I've encountered a pretty weird behavior when using auto and dynamic_cast. This is the class hierachy i have:

class BaseInterface {
public:
    virtual void someMethod()=0;
};

class Derived:public BaseInterface {
public:
    virtual void someMethod1()=0;
    void someMethod()override;
};

And of course there are some classes that implement all derived methods.

Then there is a third class which looks like this:

class ThirdClass {
public:
    void demoMethod(BaseInterface&);
    void anotherMethod(Derived&);
};

ThirdClass::demoMethod(BaseInterface& obj) {
    auto buffer=dynamic_cast<Derived&>(obj);
    anotherMethod(buffer);
}

When i compile this with gcc i get an "cannot allocate an object of abstract type" error. Whereas when i replace

auto buffer=...

with

Derived& buffer=...

everything compiles fine. Why is that the case? Is auto not deducing the right type or something?

Also i found a dirty trick to still use auto:

ThirdClass::demoMethod(Base& obj) {
    auto buffer=dynamic_cast<Derived*>(&obj);
    anotherMethod(*buffer);
}

Aucun commentaire:

Enregistrer un commentaire