0

This is a tricky answer to find using google since there are many similar questions but different.

Basically the idea is that, I have ProjectA and ProjectB where they both inherit ProjectBase. They parse the data differently but other that each having his own members they both update also the members from ProjectBase.

So when we projecta->Parse() we want to copy the ProjectBase content and use it inside projectb->Build(). Also, those classes have many more member of virtual, unique and shared ptrs.


class ProjectBase
{
protected:
    int data;

public:
    virtual void Parse() = 0;
    virtual Zip Build() = 0;
}

class ProjectA : public ProjectBase
{
    void Parse()
    {
        data = 2;
    }
    
    Zip Build()
    {

    }
}

class ProjectB : public ProjectBase
{
    void Parse()
    {
        data = 3;
    }

    Zip Build()
    {
        
    }
}


// I need to copy the content of the ProjectBase (or here it will be int data) from projecta to projectb
std::unique_ptr<ProjectA> projecta = std::make_unique<ProjectA>();
projecta->Parse();

std::unique_ptr<ProjectB> projectb = std::make_unique<ProjectB>();
// ???
// I need to use the data = 2 inside projectb->Build()
Ido
  • 2,034
  • 1
  • 17
  • 16

1 Answers1

1

This is one of the cases where object slicing is actually what you want. If you upcast the target object reference then the implicit ProjectBase copy-assignment operator will do what you want.

static_cast<ProjectBase &>(*projectb) = *projecta;

This will assign only the inherited data members of ProjectBase from *projecta to *projectb.

cdhowie
  • 158,093
  • 24
  • 286
  • 300