An alternative model that you could use, as defined by Composition over Inheritance and the Principle of One Responsibility referred to by Stefan Rolland, has implemented the following model.
First you need three different classes:
class CLog { CLogReader* m_Reader; CLogWriter* m_Writer; public: void Read(CString& strLog) { m_Reader->Read(strLog); } void Write(const CString& strNewMsg) { m_Writer->Write(strNewMsg); } void setReader(CLogReader* reader) { m_Reader = reader; } void setWriter(CLogWriter* writer) { m_Writer = writer; } };
CLogReader handles the sole responsibility of reading logs:
class CLogReader { public: virtual void Read(CString& strLog) {
CLogWriter handles the sole responsibility for logging:
class CLogWriter { public: virtual void Write(const CString& strNewMsg) {
Then, if you want your CLog to, say, write to the socket, you get CLogWriter:
class CLogSocketWriter : public CLogWriter { public: void Write(const CString& strNewMsg) {
And then install your instance CLog instance into the CLogSocketWriter instance:
CLog* log = new CLog(); log->setWriter(new CLogSocketWriter()); log->Write("Write something to a socket");
Pros The advantage of this method is that you follow the principle of shared responsibility, since each class has one purpose. This gives you the opportunity to expand one goal without dragging code that you will not modify in any way. It also allows you to change components as you like without having to create an entire new CLog class for this purpose. For example, you might have a Writer that writes to a socket, but a reader reading a local file. Etc.
Against memory management is becoming a huge problem for us. You must keep track of when to remove pointers. In this case, you need to delete them when you destroy the CLog, as well as when setting up another Writer or Reader. Doing this if links are stored elsewhere can lead to dangling pointers. This would be a great opportunity to learn about strong and weak links, which are containers of link counts that automatically delete their pointer when all links to it are lost.