Polymorphism and member shared_ptr

Testing polymorphism and virtual functions and shared_ptr, I am trying to understand the situation described in the following minimal example.

class B{
public:
  // Definition of class B
  virtual void someBMethod(){
   // Make a burger
  };
};

class C : public B {
public:
  // Definition of class C
  void someBMethod(){
   // Make a pizza
  };
};

class A{
public:
  A(B& SomeB) : Member(std::make_shared<B>(SomeB)){};
  std::shared_ptr<B> Member;
};

Now, basically, we can have

int main(){
  C SomeC;
  A SomeA(SomeC);
  A.Member->someBMethod(); // someBMethod from B is being executed.
};

If I had not included some error from my actual code in a minimal example, I think that it SomeCis sliced ​​to B, or at least someBMethodfrom, Bcalled in the last line.

Question: What should be the correct way to initialize Memberso that the called method someBMethodfrom is Ccalled?

+4
source share
2 answers

I think SomeCchopped upB

, . make_shared , . , B, copy-constructor - B SomeC.

Member , someBMethod C ?

: C , Member , . , , , , , :

A(std::shared_ptr<B> SomeB) : Member(SomeB){}

, , :

A(B& SomeB) : Member(std::shared_ptr<B>(&SomeB, [](B*){})){}

, , C , A, . "" .

, , &SomeB. , , .

+3

slicing, std::make_shared<B>(SomeB). shared_ptr, B, , - B: B::B(const B& b) C -ness SomeB.

A :

class A{
public:
  A(const std::shared_ptr<B>& pB) : pMember(pB) {}
  std::shared_ptr<B> pMember;
};

:

int main(){
  A SomeA(std::make_shared<C>());
  A.pMember->someBMethod(); // someBMethod from C is being executed.
}
+5

All Articles