C ++ 11 smart pointers and polymorphism

I am rewriting an application using C ++ 11 smart pointers.

I have a base class:

class A {};

And the derived class:

class B : public A {
  public:
  int b;
};

I have another class containing a vector with objects A or B:

class C {
  public:
  vector<shared_ptr<A>> v;
};

I have no problem constructing C with objects of A (base class), but how can I populate it with objects of B (derived class)?

I am trying to do this:

for(int i = 0; i < 10; i++) {
    v.push_back(make_shared<B>());
    v.back()->b = 1;
};  

And the compiler returns: error: "class A does not have a name named" b

+5
source share
2 answers

But how can I populate it with objects of B (derived class)?

< > B. A, .

B :

std::shared_ptr<B> b = make_shared<B>();
b->b = 1;
v.push_back(b);

, - :

  • static_cast<B*>(v.back().get()) , , , B
  • dynamic_cast ( , ),
+10
for(int i = 0; i < 10; i++) {
    auto bptr = make_shared<B>();
    v.push_back(bptr);
    bptr->b = 1;
};  
+3

All Articles