Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting Scope of #include Directives

Let's say I have a header file with a class that uses std::string.

#include <string>

class Foo
{
     std::string Bar;

     public:

     // ...
}

The user of this header file might not want std::string to be included in his/her project. So, how do I limit the inclusion to just the header file?

like image 490
Maxpm Avatar asked Dec 08 '25 01:12

Maxpm


1 Answers

The user of your class must include <string>, otherwise their compiler will not know how big a Foo object is (and if Foo's constructors/destructors are defined inline, then the compiler also won't know what constructor/destructor to call for the string member).

This is indeed an irritating side-effect of the C++ compilation model (basically inherited intact from C). If you want to avoid this sort of thing entirely, you probably want to take a look at the PIMPL idiom.

like image 169
Oliver Charlesworth Avatar answered Dec 10 '25 16:12

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!