user1939871
user1939871

Reputation:

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.

Upvotes: 4

Views: 3591

Answers (2)

PaperBirdMaster
PaperBirdMaster

Reputation: 13320

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.

Upvotes: 5

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

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.

Upvotes: 3

Related Questions