Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single class instance C++

Tags:

c++

class

Is it possible to create a class which could be constructed just one time? If you would try to create an other instance of it, a compile-time error should occure.

like image 338
rafdp Avatar asked Apr 28 '12 08:04

rafdp


People also ask

Is a single instance of a class?

In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.

What is instance of class in C?

C Classes An instance type is a struct containing variable members called instance variables and function members called instance methods. A variable of the instance type is called an instance. A class object is a global const struct variable containing class variables and class methods.

How do I create a class with just one instance?

To create a class with only one instance, make the constructor private and create a publicly accessible static reference of the object. While doing this, you don't really want to create the Singleton at startup since Singletons are used for objects which are expensive to create.

What is single instance in C++?

Singleton in C++ Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.


2 Answers

Instantiation is dynamic, at run time. Compilation errors are at compile time. So the answer is no, it's not possible to get a compilation error on any second instantiation.

You can however use a singleton, but do consider very carefully whether it's really needed.

like image 54
Cheers and hth. - Alf Avatar answered Oct 21 '22 22:10

Cheers and hth. - Alf


The classes with only one instances are called singleton classess,

There are many ways to perform that. The simplest is shown below

class MySingleton
    {
    public:
      static MySingleton& Instance()
      {
        static MySingleton singleton;
        return singleton;
      }

    // Other non-static member functions
    private:
      MySingleton() {};                                 // Private constructor
      MySingleton(const MySingleton&);                 // Prevent copy-construction
      MySingleton& operator=(const MySingleton&);      // Prevent assignment
    };
like image 26
Jainendra Avatar answered Oct 21 '22 22:10

Jainendra