4

How to make it work? Error/comment line before return 0;

#include <iostream> 
#include <vector>
#include <memory>

using namespace std;


class Base 
{
    public:   
        void foobar() { cout << "foobar"; }
};

class Derived : public Base
{
    public:

        void print() { cout << "hello world!"; }
};

int main(int argc, char *argv[]) 
{
    vector<unique_ptr<Base>> bases;
    bases.push_back(unique_ptr<Base> (new Derived()));

    //ok
    bases[0]->foobar();
    //error
    //how can I make this works?
    static_cast<Derived*> (bases[0])->print();

    return 0;
}

1 Answers1

2

To do this cast you need to get the actual stored pointer in base[0] like this:

static_cast<Derived*>(bases[0].get())->print()

EDIT:

I agree with @Tietbohl in that dynamic_cast is safer, and that downcasting can be an indicator of bad design. However there are a few situations where, downcasting makes sense, and you can be certain that it is safe.

For example, let's say that you have a factory method, that creates an object with a certain interface, but you provide a parameter indicating that you want a specific concrete class, and then you need to perform operations on the returned object:

Interface* object = factory->CreateObject([parameter specifies type ConcreteA]);

...
static_cast<ConcreteA*>(object)->FuncOnA();

In this situation, you can avoid the complications of RTTI by simply using static_cast.

imreal
  • 10,178
  • 2
  • 32
  • 48
  • Should that not be a `dynamic_cast`? – Danvil Apr 08 '14 at 19:30
  • 3
    @Danvil It doesn't have to be if you are certain the pointer can be downcasted. I don't like `dynamic_cast` because it adds the need to enable RTTI. Anyway, downcasts should be avoided when possible. – imreal Apr 08 '14 at 19:35
  • Totally agree, but I always think if you are completely sure about the type, then why is it not reflected in your design... So at least try to make an effort by using `dynamic_cast` and check for 0 ;) – Danvil Apr 08 '14 at 19:38
  • sometimes.. some answers are the most elegant –  Apr 08 '14 at 19:42
  • Rather, `dynamic_cast` is a sign of bad design. `static_cast` is not as expensive and indicates that you know the type exactly. If you do not know if a downcast works, this usually tells you that you should refactor your design – IceFire Oct 10 '19 at 08:05