How to disclose class interface but hide implementation
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
Re: How to disclose class interface but hide implementation
Quote:
Originally Posted by
AlanCCC
1. Know the implementation of the CMyClass object.
The implementation is already hidden, since your code is in your CPP file, not your H/HPP file.
Quote:
Originally Posted by
AlanCCC
2. Know the existance of the member variable m_iData and m_bFlag.
The only way to hide the private members is to use an opaque pointer, also known as the pimpl idiom.
Code:
class CMyClass
{
public:
CMyClass();
int MyFun(int a, int b);
private:
class CMyClassImpl *impl; //pointer to forward declared private implementation class
}
Then you private data members go in your CMyClassImpl class, which is kept separate from your public headers. Inside your CMyClass implementation, you can access things like m_iData with impl->m_iData.
See?
Re: How to disclose class interface but hide implementation
Quote:
Originally Posted by
AlanCCC
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.
I'd say it primarily depends on what you mean by "Know"...
1. If you just want to be able to change implementation details without impacting people using your code.
2. If you mean want to keep your code a company secret, and prevent the other developer from stealing your hard written code...
1: Just use the pimpl idiom.
2: Use the pimpl idiom, but compile it your self, and only deliver the .h of your CMyClass object. The client does not need the rest.