0

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

In MyClass.h:

class CMyClass
{
public:
    CMyClass();

    int MyFun(int a, int b);
    
protected:
    int m_iData;
    BOOL m_bFlag;    
}

In MyClass.cpp

CMyClass::CMyClass()
{
    //  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?

Thanks

Edited by Narue: Added code tags

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by vijayan121
0

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

0

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"

namespace
{
    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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.