Tohiko
Tohiko

Reputation: 1982

Best way to hide private members in a class

I have the following code in a header file

class Bar {
   public: 
      void public_foo();
   private:  
      void private_foo();
};

The implementation is hidden away in a source file

void Bar::public_foo(){
   private_foo();
}
void Bar::private_foo(){
   // Some more stuff
}

I would like to not have the private function visible in the header file. What is the best way to do this? I know of two ways:

1) Make private_foo a non-member function like this

void private_foo(Bar* this){ /* ... */ }

And call it in public_foo like this: private_foo(this). This is not very appealing to me because it's not particularly OO programming.

2) Use a hidden implementation class like this

// In header
class Bar {
   public: 
      virtual void public_foo();
      virtual ~Bar() { };
};
Bar* CreateBar();

// In Source
class Bar_impl : public Bar {
   public:
      void public_foo();
   private:  
      void private_foo();
};

Bar* CreateBar(){
    return new Bar_impl;
}

void Bar::public_foo(){
   private_foo();
}
void Bar::private_foo(){
    // Some more stuff
}

This works, but it's a bit too much for something so simple.

Is there a third (better) method?

EDIT: In response to @jdehesa, and because I like to wear the hat of a language designer, here is my ideal syntax (NOT correct C++ syntax, but one can dream)

// In header
class Bar {
   public: 
      void public_foo();
};

// In Source
classdef Bar {   // Notice my new "classdef" keyword
public: 
   void public_foo(){
   }

private:
   void private_foo(){
   }
};

One issue is that for correct memory allocation, the implementation class cannot add extra variables (public or private).

Upvotes: 1

Views: 2013

Answers (1)

Nagato
Nagato

Reputation: 79

You can use PIMPL idiom

Example:

// Pimpl idiom - basic idea
class widget {
    // :::
private:
    struct impl;        // things to be hidden go here
    impl* pimpl_;       // opaque pointer to forward-declared class
};

Upvotes: 8

Related Questions