Class having member variable with same inheritance as itself [closed]
I am writing some test code where I am creating a "Test Message" class that mimicks a "Real Message" class. The RealMessage class inherits from a class called ID that holds the ID of the message; however I want to have a different ID for the TestMessage class. The class ID is something like this: Class ID { public: ID(id) : id_(id) { } const std::string& getId(); private: std::string id_; } Since the id is private and the RealMessage class has all the fields that need to be in the TestMessage class, the only solution I thought of without changing other code or using the #define private public hack is the following: Class TestMessage : public ID { public: TestMessage() : ID("TestMessageID") { } /// Some function to set the real message data void setRealMessageData(const RealMessage& msg); private: RealMessage msg; }; Is there a better way that I could do this ? I definitely cannot change the ID class since that is in an external library, but the RealMessage I could change, but it would require potentially refactoring code which uses that class. This is the pattern the unit test uses for all other messages, but all other messages use separate class for msg payload, so that's not an issue in that case.
![Class having member variable with same inheritance as itself [closed]](https://cdn.sstatic.net/Sites/softwareengineering/Img/apple-touch-icon@2.png?v=1ef7363febba)
I am writing some test code where I am creating a "Test Message" class that mimicks a "Real Message" class. The RealMessage
class inherits from a class called ID
that holds the ID of the message; however I want to have a different ID
for the TestMessage
class. The class ID is something like this:
Class ID
{
public:
ID(id) : id_(id)
{
}
const std::string& getId();
private:
std::string id_;
}
Since the id is private and the RealMessage
class has all the fields that need to be in the TestMessage
class, the only solution I thought of without changing other code or using the #define private public
hack is the following:
Class TestMessage : public ID
{
public:
TestMessage() : ID("TestMessageID")
{
}
/// Some function to set the real message data
void setRealMessageData(const RealMessage& msg);
private:
RealMessage msg;
};
Is there a better way that I could do this ? I definitely cannot change the ID class since that is in an external library, but the RealMessage
I could change, but it would require potentially refactoring code which uses that class. This is the pattern the unit test uses for all other messages, but all other messages use separate class for msg payload, so that's not an issue in that case.