hi,

is it possible to declare constructors as private? if yes, will some one explain me how to do it or please provide some links regarding that.


thanks & regards
prasath

Dani AI

Generated

— yes. As showed, placing a constructor under a non-public access specifier prevents client code from calling it; only members, friends, or nested types can construct the object. That mechanism is commonly used to implement singletons, factory creation functions, controlled lifetime, or to block copying (older code made the copy constructor private; modern code uses = delete).

A typical modern singleton pattern (thread-safe since C++11) keeps the ctor private and deletes copy/move operations:

class Logger {
public:
  static Logger& instance() {
    static Logger inst;
    return inst;
  }

  Logger(const Logger&) = delete;
  Logger& operator=(const Logger&) = delete;

private:
  Logger() { /* init */ }
};

A factory that returns a smart pointer must construct the object from inside the class (std::make_unique cannot call a private ctor from outside), for example:

class Widget {
public:
  static std::unique_ptr<Widget> create(int p) {
    return std::unique_ptr<Widget>(new Widget(p));
  }

private:
  Widget(int x) : val(x) {}
  int val;
};

Notes: use protected (not private) if subclassing should be allowed; pre-C++11 code typically declared copy ctor/assignment private and undefined to prevent copying; since C++11 prefer = delete. For language details see the C++ reference on constructors and deleted functions, and the note on static local initialization and thread safety: , cppreference - deleted functions, cppreference - static local variables.

Recommended Answers

All 2 Replies

is it possible to declare constructors as private? if yes, will some one explain me how to do it or please provide some links regarding that.

Here's one link

>is it possible to declare constructors as private?
Yes, and it provides some valuable functionality to do so occasionally.

>if yes, will some one explain me how to do it
Just place the constructor declaration in the private section rather than the public section:

class test {
public:
  test ( int init );
private:
  test();
};

In the test class, the single argument constructor is required by the outside world because it's the only one visible, but the implementation code of the test class can also use the default constructor.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.