mardi 26 novembre 2019

How to share the struct in inheritance classes?

I would like to share a struct with multiple inheritance classes. But I am not sure how to write such codes.

This is a code I tried to write. I would like to share Info with Parent and ChildA

#include <memory>
#include <iostream>
#include <vector>

struct Info
{
    Info(int num) : 
        memberNum(num)
    {

    }

    const std::string surName = "foge";
    const int memberNum;
};


class Parent
{
public:
    Parent(std::shared_ptr<Info> info) : 
        info(info)
    {};
    virtual ~Parent() {};

protected:
    std::shared_ptr<Info> info = nullptr;
};


class ChildA : public Parent
{
public:
    ChildA(std::shared_ptr<Info> info) : 
        info(info) // error : C++ is not a nonstatic data member or base class of class
    { // error : C++ no default constructor exists for class

    };

    ~ChildA() {};

};


int main(int argc, char** argv)
{
    int num = 4;
    std::shared_ptr<Info> info = std::make_shared<Info>(num);

    std::unique_ptr<Parent> pa = std::make_unique<Parent>(info);
    std::unique_ptr<Parent> chA = std::make_unique<ChildA>(info);

    return 0;
}

I am not sure this is a good manner of writing. Does anyone have any idea? Thank you!

Aucun commentaire:

Enregistrer un commentaire