Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

troubleshooting Question

Singleton template / private constructor for Singleton instances

Avatar of forums_mp
forums_mp asked on
11 Comments1 Solution500 ViewsLast Modified:
Referencing the source below, I'm trying to prevent the case where the end user can create an instance of foo without utilzing Singleton::Instance.  IOW:  I"m trying to prevent this:
  foo f;
To do this I thought about making the constructor of foo protected but that's problematic for the singleton class.  I'm not sure how to achieve the objective without making foo a friend of Singleton which is not acceptable.  How can I achieve my objective?
# include <iostream>
# include <numeric>

template <typename T>
class Singleton
  //friend class foo; //not acceptable
   Singleton() {}
   virtual ~Singleton() {}
   static T& Instance() 
     static T obj ; 
     return ( obj ) ;
   Singleton(const Singleton &s);
   Singleton &operator = (const Singleton &s);

class foo : public Singleton < foo > 
  int x ; 
  //foo() {}
public :
  void SetX ( int const in ) 
  { x = in ; }
  int GetX () const { return ( x ) ; }

int main() 
  foo f; 
  f.SetX ( 5 ) ;
  foo& ff = foo::Instance();
  std::cout << ff.GetX() << std::endl;
Avatar of evilrix
evilrixFlag of United Kingdom of Great Britain and Northern Ireland imageSenior Software Engineer (Avast)

Our community of experts have been thoroughly vetted for their expertise and industry experience.

This problem has been solved!
Unlock 1 Answer and 11 Comments.
See Answers