tags:

views:

61

answers:

3

This is the code:

#include <map>
class Hidden {
private:
  friend class Visible;
  Hidden(); { /* nothing */ }
};
class Visible {
public:
  void f() {
    std::map<int, Hidden> m;
    m[1] = Hidden(); // compilation error, class Hidden is private
  }
};

The code doesn't compile because the constructor of class Hidden is private for class std::map. Obviously, I don't want to make class std::map a friend of Hidden. But what should I do here? Thanks in advance!

A: 
class Hidden {
public:
    static Hidden* create(){return (new Hidden());} 
private:
    friend class Visible;
    Hidden(){ /* nothing */ }
};

class Visible {
public:
  void f() {
    std::map<int, Hidden*> m;
    m[1] = Hidden::create(); 
  }
};

Container would require an accessible constructor to create objects. If data members are there you would have to define your destructor properly to clear up the memory allocation.

DumbCoder
+2  A: 

Add the map as a friend class:

#include <map>
class Hidden {
private:
  friend class Visible;
  friend class std::map<int, Hidden> ;
  Hidden() {}
};
class Visible {
public:
  void f() {
    std::map<int, Hidden> m;
    m[1] = Hidden(); // compilation error, class Hidden is private
  }
};

Of course, it means you have to declare all Hidden users inside Hidden, but that's exactly the point of the "private class" pattern you're using...

paercebal
@aaa : I did not declare the template map as a friend. Only its instanciation as a map of [int, Hidden]. So There is no problem of portability.
paercebal
A: 

For your class Hidden, map is just another class and unless you explicitly make map a friend of Hidden, it map won't be able to access Hidden's constructor.

The approach given by paercebal must work as he's making map the friend of your class Hidden.

hype