I want to write a C++ class, like this:

In MyClass.h:

class CMyClass

    int MyFun(int a, int b);
    int m_iData;
    BOOL m_bFlag;    

In MyClass.cpp

    //  Some initialization codes

int CMyClass::MyFun(int a, int b)
    //  Implemenation of MyFun

Now I want to let another developer to use CMyClass, but only want him to be able to:

1. Construct a CMyClass object.
2. Call MyFun function.

and PREVENT him to:

1. Know the implementation of the CMyClass object.
2. Know the existance of the member variable m_iData and m_bFlag.

Now I can put MyClass.h and MyClass.cpp in a static library and compile it, then send the compiled static library as well as only the MyClass.h to the developer, but he will still able to know the protected memory variables m_iData and m_bFlag, and based on them, he can guess the implementation of the MyFun. How to prevent this?


Edited 5 Years Ago by Narue: Added code tags

Google the "pimpl idiom" (no, that's not a typo) for the usual way in which we hide a class' implementation details.

Alternatively, use a pure object-oriented interface.

////////// header my_class.h ////////////////////////////
// include guard

#include <memory>

struct my_class
    static std::shared_ptr<my_class> create(int,int) ;

    virtual ~my_class() ;

    virtual int my_fun( int a, int b ) = 0 ;

    // virtual ... = 0 ;
    // virtual ... = 0 ;
////////// implementation my_class.cc ////////////////////////////
# include "my_class.h"

    struct my_class_impl : my_class
        my_class_impl( int, int ) ;

        virtual int my_fun( int a, int b ) override ;

        // virtual ... override ;
        // virtual ... override ;
    // my_class_impl member definitions

std::shared_ptr<my_class> my_class::create( int a, int b )
    return std::make_shared<my_class_impl>(a,b) ; 
This article has been dead for over six months. Start a new discussion instead.