Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an include "Private"?

Is there any way I can include a file in a class so it can use it but not allow anything including that class into the scope to be able to use it? To simplify lets say I have the iostream header in a class called IO and I make IO be able to write things with the cout function but not let anything that includes IO to be able to use anything in the iostream header. That's not what I want to do but I need to figure this out so I don't "double define" things.


2 Answers

Yes you can, just include it in the cpp not in the h.

// IO.h
// note the lack of #include <iostream>

class IO
{
     // IO stuff...
     void f();
};

Then on the cpp:

// IO.cpp
#include "IO.h"
#include <iostream>

IO::void f()
{
    std::cout << "Hello world!" << '\n';
}

When you include IO.h in some other file you're not including <iostream>, take a look to the compilation unit concept.

like image 181
PaperBirdMaster Avatar answered Oct 27 '25 19:10

PaperBirdMaster


A common solution to that problem is to declare IO in a separate header/source file pair. In the header you forward declare the classes you will be needing and in the source file you include the header you need. This way the actual contents of the header are only accessible in the source file.

like image 24
Ivaylo Strandjev Avatar answered Oct 27 '25 18:10

Ivaylo Strandjev



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!