tags:

views:

133

answers:

3

I want to hide an implementation in implementation file. If the object is not public, I don't want the object's header to leak everywhere my class is used.

Suppose I have header file A.h for my class A:

#include "Foo.h"

class A{
    private:
        Foo foo;
    public:
        do_stuff();
};

Now wherever I would include A.h, Foo.h also would be included. But I have no use for class Foo anywhere outside of class A. I would rather not have this #include "Foo.h" line. Is there any way to move the declaration of 'foo' variable inside the implementation A.cpp?

I suspect one possible solution involves adding a layer of abstract class (interface analogy). Is it the best solution?

Thank you.

+11  A: 

Use a pointer to Foo and allocate it dynamically, rather than using a member object. Then you only need to include Foo.h in A.cpp.

class Foo;

class A{
    private:
        Foo* foo;
    public:
        do_stuff();
}
David
+1, this is the "PIMPL" idiom, and is standard practice.
greyfade
+1 to the answer and +1 to greyfade for pointing out that it's basically a pimpl (opaque pointer to private implementation details).
Nice! Thank you. I remember seeing the idiom, but I didn't pay attention to it at the time.
Bear
+1  A: 

David's got the right answer. I'll refer to this article for a little more treatment on this kind of "opaque pointer" trick, as you can get more elaborate with it, depending on your needs:

http://en.wikipedia.org/wiki/Opaque_pointer

Also, it's a good idea to use shared_ptr types for this purpose instead of raw pointers like the sample. This will take care of cleaning up resources for you automatically, once the last reference to Foo goes out of scope.

holtavolt
I'm a fan of shared pointers, but I think its overkill in this case. Its usually used when ownership is complicated. If foo is only used in the A object that creates it, there is no ownership problems.
KeithB
A: 

Yes. Choose yer poison!

Option 1. Forward declaration in interface.

class A {
    private:
        class Foo;
        Foo* foo;
};

Option 2. ABC.

// A.hpp
class A {
    public: virtual void do_stuff() = 0;
};

// A.cpp
class A_impl : public A {
   class Foo { /*etc*/ };
   Foo foo;
   void do_stuff (){...}
};

Option 3. Private is private. It's "hidden" as far as the public API goes, which is all that matters:

class A {
    private:
        class Foo {
            ...
        };
        private_::Foo foo;
    public:
        do_stuff();
};

Option 4. Just put the declaration in a "non-public" namespace.i.e., omit it from documentation and name it something to frighten away prying eyes:

namespace private_ {
   class Foo {
      ...
   };
}
class A {
    private:
        private_::Foo foo;
    public:
        do_stuff();
};
John