how to allow only one specific class to create other class instances

Viewed 65

MyDataConatiner is kind of facade to MyData.

I Dont want to allow other classes to create Mydata . it has some logic of lazy instantiation that I want to keep in MyDataConatiner .

thought about something like private ctor with friend class , but I am not sure.

or is it something with one of factory design patterns

1 Answers

One way is to make MyDataContainer a friend of MyData as shown below:

class MyData 
{
  //befriend MyDataContainer so that MyDataContainer can create object of type MyData
  friend class MyDataContainer;
  
  //private converting ctor that can be used by MyDataContainer but not normal users
  MyData(int)
  {
      
  }
};
class MyDataContainer
{
    public: 
        //add method(s) for creating MyData object 
        
    //other code here   
};
Related