When exporting a class to a static lib in C++, how could I conceal the private function of the class?

StackOverflow https://stackoverflow.com/questions/21693052

  •  09-10-2022
  •  | 
  •  

Question

EG,

//this is myclass.h
class myclass
{
public:
  int publicfunction();
private:  
  int myprivatefunction();
};

//myclass.cpp

#include "myclass.h"
int myclass::publicfunction()
{myprivatefunction();
blabla...}

int myclass::privatefunction()
{blabla...}

So, for users can access the class,we will provide the header file to the users. But shouldn't we conceal the internal implement details of the class??? I mean, when the users get myclass.h, they will find that the class contains a private function myprivatefunction

Was it helpful?

Solution 2

Your header file isn't just your public interface. It's a description of your data layout for the compiler. It is perfectly normal that the private members get shown in the header file. private is not a security mechanism and never will be.

It's a bit strange, but it falls out from a simple yet efficient way of going about the problem.

OTHER TIPS

You can export the private members inside a struct

//this is myclass.h
class myclass{
private:
   struct myClassPrivateMembers;
   myClassPrivateMembers* privParts;
public:
   // ...
};

And in the *.cpp file:

//this is myclass.cpp
struct *myClassPrivateMembers{
   int myprivatefunction();
}

myclass::myclass(){
   privParts = new myClassPrivateMembers;
};

That way the user won't be able to see things you hidden inside myClassPrivateMembers, because they'll be inside the *.cpp file, not declared in the header file.

This is widelly known as the "pimpl" idiom.

You might as well separate your interface and your implementation.

myinterface.h

class myinterface
{
public:
  virtual int publicfunction() = 0;
};

myclass.h

class myclass : public myinterface
{
public:
  virtual int publicfunction();
private:
  int privatefunction();
};

myclass.cpp

#include "myclass.h"
int myclass::publicfunction()
{myprivatefunction();
blabla...}

int myclass::privatefunction()
{blabla...}

You don't have to expose myclass.{h,cpp} to library users.

But this might be an overkill... (I would call this "Java folks' way")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top