Tuesday, July 14, 2009

In microsoft visual c++ , how can i hide private members of a class in a static link library?

i wrote a static link library in two files : code.cpp and header.h , header.h includes the interface of a class named Class1 , which have private members and public members , and code.cpp includes the implementation of that class , i dont want the programmer who uses the static link library to see the private members decleration of the class (Class1) , if i give header.h to the programmer he will know the declaration of the private members , and if i exclude the private members of his copy of header.h , it class (Class1) will not work.

In microsoft visual c++ , how can i hide private members of a class in a static link library?
One way to do it is to make Class1 call some other class for all actual implementation. So you make a new class, Class1Impl, which does all the real work. Class1 has a pointer to Class1Impl, and all of the member functions of Class1 call the appropriate member function of Class1Impl. You don't need to give out the header for Class1Impl as it can just be predeclared at the top of the Class1 declaration.


Ex:


//class1.h


class Class1Impl;





class Class1


{


private:


Class1Impl* m_pImpl;





public:


Class1();


void DoStuff();


};





//Class1.cpp


#include "Class1.h"


#include "Class1Impl.h"





Class1::Class1()


{


m_pImpl = new Class1Impl;


}





void Class1::DoStuff()


{


m_pImpl-%26gt;DoStuff();


}





//class1impl.h


//hidden, never give this source out


class Class1Impl


{


private:


long m_lHiddenVal;


public:


void DoStuff() { printf("Woo! %d", m_lHiddenVal); }


};


No comments:

Post a Comment