0

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

This is an example code I want to write, but the error occurs in this code. I would like to share struct Info with Parent and ChildA. Once I set Info in main, I wouldn't like to change the value in Info and want to access values in Info from Parent and ChildA . So I pass Info to 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;
};


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!

Masahiro
  • 155
  • 9
  • "I would like to share a struct with multiple inheritance classes." Please explain more. What do you want to achieve? What do you expect to do when it works? Please give examples. – Yunnosch Nov 26 '19 at 08:13
  • 1
    Use `ChildA(std::shared_ptr info) : Parent(info)` , that `info(info)` doesn't belong there; that's taken care of for you in the parent class via his ctor. It's his member. – WhozCraig Nov 26 '19 at 08:15
  • `std::shared_ptr info = nullptr;` can be simplified to `std::shared_ptr info;`. – Evg Nov 26 '19 at 08:18
  • @Yunnosch Thank you for your comment, I update the post and explain more – Masahiro Nov 26 '19 at 08:25
  • @Evg Thank you for your comment, I update the code. – Masahiro Nov 26 '19 at 08:26

1 Answers1

2

You need to change

ChildA(std::shared_ptr<Info> info) : 
    info(info)

};

to

ChildA(std::shared_ptr<Info> info) : 
    Parent(info)
{

};

Because info is part of Parent, it is the one that needs to initialise it. See this answer for more info.

ShadowMitia
  • 2,411
  • 1
  • 19
  • 24