Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Base class and private header

I'm writing a library in C++ and have a class hierarchy like this:

message.h file (in ./mylib/src)

class Message
{
};

request.h file (in ./mylib/include/mylib)

#include "message.h"

class Request : public Message
{
};

response.h file (in ./mylib/include/mylib)

#include "message.h"

class Response : public Message
{
};

I want everything in my mylib/src folder to be hidden from user and want only to distrubute files in mylib/include. But the problem is as both requst.h and response.h #include message.h so user will get a "No such file" error when #including request.h and response.h. Is there a way to work around this problem?

like image 920
jpen Avatar asked Dec 27 '22 10:12

jpen


1 Answers

You can simply provide a public interface for Message and keep the actual class hidden:

class IMessage
{
    Message* pImpl;
};

Distribute this header and use a forward declaration for Message.

Another option would be to use composition instead of inheritance (you'll need pointers as members, not the full object).

like image 130
Luchian Grigore Avatar answered Dec 28 '22 23:12

Luchian Grigore