I have an object of class Message, which can be written and subsequently updated. As far as I can see, MessageUpdate IS-A MessageWrite:
class MessageWrite
{
protected:
void setVersion(int version_) {...}
void setReceiveTime(int tmReceive_) {...}
Message _msg;
};
class MessageUpdate:public MessageWrite
{
//ONLY setVersionShould be accessible here, NOT setReceiveTime
};
Is there a combination of method access level and inheritance level that can help achieve this?
I know that MessageUpdate can be simply made base class, but there’s the rub: it leads to diamond pattern in case i want to extend the message class. Consider:
class MessageUpdate {...};
class MessageWrite: public MessageUpdate {...};
//Now, while extending:
class AdminMessageUpdate:public MessageUpdate {...};
class AdminMessageWrite: public AdminMessageUpdate, public MessageWrite //DIAMOND Pattern!!
Where’e the gap in my understanding of inheritance? And is there any completely different way to achieve this logic without the multiple inheritance (as shown in latter code piece)?
Since all members of
MessageWriteareprotected, you could just makesetReceiveTime()privateinsideMessageUpdate, so classes inheriting fromMessageUpdatewould not be able to access it. But I still have some issues with your design, such as:How is it that your design avoids the diamond? Wouldn’t it equally lead to:
Why do you think
MessageUpdateIS-AMessageWritewhen you later say it is not (by specifying that not all ofMessageWriteapplies to it)? If this code must not be valid:then
MessageUpdateIS-NOT-AMessageWrite. If my code should be valid, then there is no reason to avoid access tosetReceiveTime()inMessageUpdate.And you would probably be better off by creating a base class
AdminMessageand then inheriting directly from it to avoid the diamond: