Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

c++ - C++11 smart pointers and polymorphism

I'm rewriting an application using c++11 smart pointers.

I have a base class:

class A {};

And a derived class:

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

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

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

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

I'm trying 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’ has no member named ‘b’

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

You are filling it with (pointers to) B objects. However, the pointers' static type refers to the base class A, so you cannot directly use these to access any members of the derived class.

In your simple example, you could simply keep hold of a pointer to B and use that:

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

If you don't have access to the original pointer, then you will need some kind of polymorphism:

  • use static_cast<B*>(v.back().get()) if you know that all objects have type B
  • use a virtual function or dynamic_cast (which requires the base class to contain a virtual function to work) if the objects might have different types

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...