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!