How do I hide class implementations using headers?

Hi,
I am currently working on data abstraction. I was able to write a class (a simple clock, see Malik's C++ book, Chapter 12 for reference). As you can imagine, I am quite new to programming and C++.

Well, now I created a header file clock.h that includes the class definition and function prototypes as well as a implementation.cpp file with the implementation details of the class.

I managed to include all this in my program.cpp and compile it (using dev c++). Everything works exactly as I want it to.

So now my question is, how can I create ... I am not sure how it is called ... a header, but without revealing to the user how the functions are implemented.
Basically the user should get a file (the object code of the header + implementation.cpp?) and simply #include it into his own program.

So instead of giving the original header + implementation.cpp to the user I want to hide how my class does its stuff and instead just provide some file that can be included and then used in a program (I will write a documentation how to use the class).

I am not sure how all this is called, I am sure there is some name for it...

Thanks a lot for your help!
I can see two ways to interpret this question.

The first is that you are looking to make a static library. Define your class like this:

1
2
3
4
5
6
// Foo.h
class Foo
{
public:
    void bar();
};


1
2
3
4
5
6
// Foo.cpp
#include <iostream>
void Foo::bar()
{
    std::cout << "Foo::bar" << std::endl;
}


Now compile your project as a static library. I don't know if this is even possible in DevC++, but in Visual studio you'll get a .lib file. In your other solution, link to the .lib file, include the header, and you're good to go.

You can also create dynamic libraries (DLLs or .so), but that's a little tougher because you have to deal with entry points.
Last edited on
The second interpretation is to assume you already know about static libraries and want to hide all private members in your class. In that case you want to use the pimpl design strategy. Check this out:
1
2
3
4
5
6
7
8
9
10
// Foo.h
class Foo_impl; // Implementation is in this class, it's forward declared only.

class Foo
{
    Foo_impl* pimpl; // we know something exists, but implementation is hidden
public:
    Foo();
    void bar(); // bar is an interface which will call some public method of Foo_impl;
};

1
2
3
4
5
// Foo.cpp -- This is in your library so it's completely hidden
#include <Foo_impl.h>

Foo::Foo() : pimpl( new Foo_impl() ) {}
void Foo::bar() { pimpl->bar(); }
Last edited on
> You can also create dynamic libraries (DLLs or .so),
> but that's a little tougher because you have to deal with entry points.
I don't see entry points in http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html
Static libraries was what I was looking for :)

Thanks a lot!
Topic archived. No new replies allowed.