Search code examples
c++templatesstdvectorunique-ptremplace

Vector of Base unique_ptr causes object slicing on emplace_back(new T())


I'm trying to pass a type as a argument to a method that will properly construct and push a object to a vector of unique_ptr, however the created object is always the Base object. This happens when using emplace_back(), the same works fine if I just instantiate the object.

Constructing the object outside the vector works fine, however I'm not sure how to move the pointer to the vector after.

body_parts.hpp

#include <vector>
#include <string>
#include <fmt/core.h>

using namespace std;

namespace uhcr {

class body_part
{
  public:
    string name = "Generic";

    template <class T>
    void add_body_part()
    {
      this->body_parts.emplace_back<T*>(new T());
      fmt::print("{}\n", this->body_parts.back()->name);
    }

  private:
    vector<unique_ptr<body_part>> body_parts;

};

class torso : public body_part
{
  public:
    string name = "Torso";
    
};

}

character.hpp

#include <string>

#include "components/body_parts.hpp"

using namespace std;

namespace uhcr {
  
class character : public body_part
{
  public:
    string name = "Character";
    
};

}

main.cpp

#define FMT_HEADER_ONLY
#include <memory>
#include <fmt/core.h>
#include "src/character.hpp"

using namespace fmt;
using namespace uhcr;

void create_human() {
  character human;
  human.add_body_part<torso>();
}

int main(void) {
  create_human();  
  return 1;
}

The error is at add_body_part(), when running this code it prints "Generic".


Solution

  • You have multiple data members named name in your subclasses. You probably want to assign values to the member in body_part, not declare new members that shadow it.

    class body_part
    {
      public:
        body_part() = default;
        string name = "Generic";
    
        template <class T>
        void add_body_part()
        {
          this->body_parts.emplace_back<T*>(new T());
          fmt::print("{}\n", this->body_parts.back()->name);
        }
      protected:
        body_part(std::string name) : name(name) {}
    
      private:
        vector<unique_ptr<body_part>> body_parts;
    
    };
    
    class torso : public body_part
    {
      public:
        torso() : body_part("Torso") {}
        
    };
    
    class character : public body_part
    {
      public:
        character() : body_part("Character") {}
        
    };