I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?
Should we have a getInstance() method inside the class?
There are a few scenarios for having private constructors:
Restricting object creation for all but friends; in this case all constructors have to be private
class A
{
private:
A () {}
public:
// other accessible methods
friend class B;
};
class B
{
public:
A* Create_A () { return new A; } // creation rights only with `B`
};
Restricting certain type of constructor (i.e. copy constructor, default constructor). e.g. std::fstream doesn't allow copying by such inaccessible constructor
class A
{
public:
A();
A(int);
private:
A(const A&); // C++03: Even `friend`s can't use this
A(const A&) = delete; // C++11: making `private` doesn't matter
};
To have a common delegate constructor, which is not supposed to be exposed to the outer world:
class A
{
private:
int x_;
A (const int x) : x_(x) {} // common delegate; but within limits of `A`
public:
A (const B& b) : A(b.x_) {}
A (const C& c) : A(c.foo()) {}
};
For singleton patterns when the singleton class is not inheritible (if it's inheritible then use a protected constructor)
class Singleton
{
public:
static Singleton& getInstance() {
Singleton object; // lazy initialization or use `new` & null-check
return object;
}
private:
Singleton() {} // make `protected` for further inheritance
Singleton(const Singleton&); // inaccessible
Singleton& operator=(const Singleton&); // inaccessible
};
A private constructor is commonly used with Builder methods, for example in the Named Constructor idiom.
class Point
{
public:
static Point Polar(double, double);
static Point Cartesian(double, double);
private:
Point(double,double);
};
In this (typical) example, the Named Constructor idiom is used to make it explicitly which coordinate system is used to build the Point object.
A private constructor is useful when you want to control the object creation of a class.
Let’s try in code:
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
};
int main()
{
aTestClass a;
aTestClass *anObject;
}
The line aTestClass a causes an error because this line is indirectly trying to access the private constructor. Comment out this line and run the program. It runs absolutely fine. Now the question is how to create the object in a such case. Let's write another program.
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
aTestClass* getAnObject() ///// A public method create an object of this class and return the address of an object of that class
{
return (new aTestClass);
}
};
int main()
{
//aTestClass a;
aTestClass *anObject = NULL;
anObject = anObject->getAnObject();
}
The output is
Object created
so we have created an object of the class containing a private constructor.
Use this concept to implement a singleton class
Yes, this is commonly used in the Singleton pattern where the object is accessed through a static member function.
If some constructor is private, it means that no one but the class itself (and friends) should be able to create instances of it using that constructor. Therefore, you can provide static methods like getInstance() to create instances of the class or create the instances in some friend class/method.
It depends on why the constructor was made private in the first place (you should ask whoever wrote the class you are editing). Sometimes a constructor may be made private to disallow copy construction (while allowing construction through some other constructor). Other times a constructor may be made private to disallow creating the class except by the class's "friend"s (this is commonly done if the class is a "helper" that should only be used by the class(es) for which the helper class was created). A constructor may also be made private to force the use of a (usually static) creation function.
If you create a private constructor you need to create the object inside the class
#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}
A private constructor in C++ can be used for restricting object creation of a constant structure. And you can define a similar constant in the same scope like enum:
struct MathConst{
static const uint8 ANG_180 = 180;
static const uint8 ANG_90 = 90;
private:
MathConst(); // Restricting object creation
};
Access it like MathConst::ANG_180.
Related
I have a question about private constructors in C++. If the constructor is private, how can I create an instance of the class?
Should we have a getInstance() method inside the class?
There are a few scenarios for having private constructors:
Restricting object creation for all but friends; in this case all constructors have to be private
class A
{
private:
A () {}
public:
// other accessible methods
friend class B;
};
class B
{
public:
A* Create_A () { return new A; } // creation rights only with `B`
};
Restricting certain type of constructor (i.e. copy constructor, default constructor). e.g. std::fstream doesn't allow copying by such inaccessible constructor
class A
{
public:
A();
A(int);
private:
A(const A&); // C++03: Even `friend`s can't use this
A(const A&) = delete; // C++11: making `private` doesn't matter
};
To have a common delegate constructor, which is not supposed to be exposed to the outer world:
class A
{
private:
int x_;
A (const int x) : x_(x) {} // common delegate; but within limits of `A`
public:
A (const B& b) : A(b.x_) {}
A (const C& c) : A(c.foo()) {}
};
For singleton patterns when the singleton class is not inheritible (if it's inheritible then use a protected constructor)
class Singleton
{
public:
static Singleton& getInstance() {
Singleton object; // lazy initialization or use `new` & null-check
return object;
}
private:
Singleton() {} // make `protected` for further inheritance
Singleton(const Singleton&); // inaccessible
Singleton& operator=(const Singleton&); // inaccessible
};
A private constructor is commonly used with Builder methods, for example in the Named Constructor idiom.
class Point
{
public:
static Point Polar(double, double);
static Point Cartesian(double, double);
private:
Point(double,double);
};
In this (typical) example, the Named Constructor idiom is used to make it explicitly which coordinate system is used to build the Point object.
A private constructor is useful when you want to control the object creation of a class.
Let’s try in code:
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
};
int main()
{
aTestClass a;
aTestClass *anObject;
}
The line aTestClass a causes an error because this line is indirectly trying to access the private constructor. Comment out this line and run the program. It runs absolutely fine. Now the question is how to create the object in a such case. Let's write another program.
#include <iostream>
using namespace std;
class aTestClass
{
aTestClass() ////////// Private constructor of this class
{
cout << "Object created\n";
}
public:
aTestClass* getAnObject() ///// A public method create an object of this class and return the address of an object of that class
{
return (new aTestClass);
}
};
int main()
{
//aTestClass a;
aTestClass *anObject = NULL;
anObject = anObject->getAnObject();
}
The output is
Object created
so we have created an object of the class containing a private constructor.
Use this concept to implement a singleton class
Yes, this is commonly used in the Singleton pattern where the object is accessed through a static member function.
If some constructor is private, it means that no one but the class itself (and friends) should be able to create instances of it using that constructor. Therefore, you can provide static methods like getInstance() to create instances of the class or create the instances in some friend class/method.
It depends on why the constructor was made private in the first place (you should ask whoever wrote the class you are editing). Sometimes a constructor may be made private to disallow copy construction (while allowing construction through some other constructor). Other times a constructor may be made private to disallow creating the class except by the class's "friend"s (this is commonly done if the class is a "helper" that should only be used by the class(es) for which the helper class was created). A constructor may also be made private to force the use of a (usually static) creation function.
If you create a private constructor you need to create the object inside the class
#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}
A private constructor in C++ can be used for restricting object creation of a constant structure. And you can define a similar constant in the same scope like enum:
struct MathConst{
static const uint8 ANG_180 = 180;
static const uint8 ANG_90 = 90;
private:
MathConst(); // Restricting object creation
};
Access it like MathConst::ANG_180.
I am a new c++ beginner.I have added private access identifier.Why does it throw this error?Thanks
class test
{
private:
test()
{
};
~test()
{
};
public: void call()
{
cout<<"test"<<endl;
} ;
};
error:
error: 'test::test()' is private|
If a constructor is private, you can't construct (define) an object of the class from outside the class itself (or outside a friend function).
That is, this is not possible:
int main()
{
test my_test_object; // This will attempt to construct the object,
// but since the constructor is private it's not possible
}
This is useful if you want to limit the construction (creation) of object to a factor function.
For example
class test
{
// Defaults to private
test() {}
public:
static test create()
{
return test();
}
};
Then you can use it like
test my_test_object = test::create();
If the destructor is private as well, then the object can't be destructed (which happens when a variables (objects) lifetime ends, for example when the variable goes out of scope at the end of a function).
Consider I want to wrap some library code inside an object. That library needs to be set up and initialized by calling some function inside the constructor of that wrapper class.
The librarie's "objects" then diverge into creating more, different "objects" that the wrapper class wraps in form of yet another wrapper object that should be a plain member of that class.
But as far as I see it, members of classes can only be initialized or created by calling their constructor in the initalizer list of the constructor. The execution of these bits of code preceed the constructor of the actual class that does the initialization of the library and its environment, making it impossible for me to actually initialize that member object as a member and instead force me to initialize it as a pointer to the 2nd wrapper, because its constructor must be called manually within the first constructor's code.
Example:
class A {
public:
A() {
if(!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
ptr_to_some_library_metadata *a = library_function(); /*Needs to
be called after wrapped_library_init() or needs a pointer to some
wrapped object created inside this constructor */
//initialize b
}
private:
B b; //Wants to be a member but can not
};
class B {
B(ptr_to_some_library_metadata *a);
}
Member objects can only be constructed in the member initializer list. There are a few techniques which can be used to make it possible to initialize an object, though:
Use a helper [lambda] function doing the necessary extra work before return a suitable object. For example:
A()
: B([]{
if (!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
return library_function();
}()) {
}
You can delay construction by using a union with just the appropriate member. When using this technique the member needs to be explicitly destructed, for example:
class A {
union Bu { B b };
Bu b;
public:
A() {
if (!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
new(&b.b) B(library_function());
}
~A() {
b.b.~B();
}
// ...
};
I'd personally use the first approach. However, there are cases when using a union to delay construction is helpful.
Initializer lists are there to use another constructor than the default constructor.
But nothing impedes you for creating a custom function that will initialize b:
class A {
public:
A():b(init()) {
}
private:
B b; //Wants to be a member but can not
static B init()
{
if(!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
ptr_to_some_library_metadata *a = library_function(); /*Needs to
be called after wrapped_library_init() or needs a pointer to some
wrapped object created inside this constructor */
return B(a);
}
};
Wrap your library inside a class:
class LibraryWrapper
{
public:
LibraryWrapper()
{
if(!wrapped_library_init()) {
exit(CRITICAL_ERROR);
}
lib_data.reset(library_function()); /*Needs to
be called after wrapped_library_init() or needs a pointer to some
wrapped object created inside this constructor */
}
//~LibraryWrapper() {/**/}
//LibraryWrapper(const LibraryWrapper&) {/**/} // =delete; ?
//LibraryWrapper& operator=(const LibraryWrapper&) {/**/} // =delete; ?
//private: // and appropriate interface to hide internal
std::unique_ptr<ptr_to_some_library_metadata, CustomDeleter> lib_data;
};
class B {
public:
explicit B(ptr_to_some_library_metadata *a);
// ...
};
And use extra member or inheritance:
class A
{
public:
A() : b(lib.lib_data.get()) {}
private:
LibraryWrapper lib; // placed before B
B b;
};
I like to experiment around as I learn more about coding. I have a program that would only require a single instance of a struct for the life of it's runtime and was wondering if it's possible to create a singleton struct. I see lot's of information on making a singleton class on the internet but nothing on making a singleton struct. Can this be done? If so, how?
Thanks in advance. Oh, and I work in C++ btw.
A class and a struct are pretty much the same thing, except for some minor details (such as default access level of their members). Thus, for example:
struct singleton
{
static singleton& get_instance()
{
static singleton instance;
return instance;
}
// The copy constructor is deleted, to prevent client code from creating new
// instances of this class by copying the instance returned by get_instance()
singleton(singleton const&) = delete;
// The move constructor is deleted, to prevent client code from moving from
// the object returned by get_instance(), which could result in other clients
// retrieving a reference to an object with unspecified state.
singleton(singleton&&) = delete;
private:
// Default-constructor is private, to prevent client code from creating new
// instances of this class. The only instance shall be retrieved through the
// get_instance() function.
singleton() { }
};
int main()
{
singleton& s = singleton::get_instance();
}
Struct and class are in C++ almost the same (the only difference is default visibility of members).
Note, that if you want to make a singleton, you have to prevent struct/class users from instantiating, so hiding ctor and copy-ctor is inevitable.
struct Singleton
{
private:
static Singleton * instance;
Singleton()
{
}
Singleton(const Singleton & source)
{
// Disabling copy-ctor
}
Singleton(Singleton && source)
{
// Disabling move-ctor
}
public:
Singleton * GetInstance()
{
if (instance == nullptr)
instance = new Singleton();
return instance;
}
}
Conceptually, a struct and a class are the same in C++, so a making singleton struct is the same as making a singleton class.
The only difference between class and struct are the default access specifiers and base class inheritance: private for class and public for struct. For example,
class Foo : public Bar
{
public:
int a;
};
is the same as
struct Foo : Bar
{
int a;
};
So, there is no fundamental difference when it comes to singletons. Just make sure to read about why singletons are considered bad.
Here's a simple implementation:
struct singleton
{
static singleton& instance()
{
static singleton instance_;
return instance_;
}
singleton(const singleton&)=delete; // no copy
singleton& operator=(const singleton&)=delete; // no assignment
private:
singleton() { .... } // constructor(s)
};
First off, struct and class only refer to the default access of members. You can do everything with a struct that you can do with a class. Now if you were referring to POD structs, things get more complicated. You can't defined a custom constructor, so there's no way to enforce only a single object creation. However, there's nothing stopping you from simply only instantiating it once.
class and struct is almost a synonyms in C++. For singleton use case they are complete synonyms.
I want to have a class hierarchy and be able to create objects from it only inside a Factory.
Example:
class Base
{
protected:
Base(){};
virtual void Init(){};
friend class Factory;
};
class SomeClass : public Base
{
public://I want protected here! Now it's possible to call new SomeClass from anywhere!
SomeClass(){};
void Init(){};
};
class Factory
{
public:
template<class T>
T* Get()
{
T* obj = new T();
obj->Init();
return obj;
}
};
int main()
{
Factory factory;
SomeClass *obj = factory.Get<SomeClass>();
}
My problem is that I want to be able to make objects only from Factory, but I don't want to declare friend class Factory in every class derived from Base.
Is there any way to propagate friend in derived classes? Is there any other way to achieve this behavior?
No, it's deliberately impossibile.
Is an issue by encapsulation.
Suppose to have a class "PswClass" that manage any password, that is cascade friend with other class: if I inherit from PswClass:
class Myclass : public PswClass {
.......
}
In this way I can, maybe, have access to field that it would be private.
Friendship is neither inherited nor transitive, as described here: friend class with inheritance.
After a little experimentation, and making some use of this hack How to setup a global container (C++03)?, I think I have found a way give the "factory" unique rights to create the objects.
Here's a quick and dirty code. (Scroll towards the bottom to see the hack.)
class Object {};
class Factory {
public:
// factory is a singleton
// make the constructor, copy constructor and assignment operator private.
static Factory* Instance() {
static Factory instance;
return &instance;
}
public: typedef Object* (*CreateObjectCallback)();
private: typedef std::map<int, CreateObjectCallback> CallbackMap;
public:
// Derived classes should use this to register their "create" methods.
// returns false if registration fails
bool RegisterObject(int Id, CreateObjectCallback CreateFn) {
return callbacks_.insert(CallbackMap::value_type(Id, createFn)).second;
}
// as name suggests, creates object of the given Id type
Object* CreateObject(int Id) {
CallbackMap::const_iterator i = callbacks_.find(Id);
if (i == callbacks_.end()) {
throw std::exception();
}
// Invoke the creation function
return (i->second)();
}
private: CallbackMap callbacks_;
};
class Foo : public Object {
private: Foo() { cout << "foo" << endl; }
private: static Object* CreateFoo() { return new Foo(); }
public:
static void RegisterFoo() {
Factory::Instance()->RegisterObject(0, Foo::CreateFoo);
}
};
class Bar : public Object {
private: Bar() { cout << "bar" << endl; }
private: static Object* CreateBar() { return new Bar(); }
public:
static void RegisterBar() {
Factory::Instance()->RegisterObject(1, Bar::CreateBar);
}
};
// use the comma operator hack to register the create methods
int foodummy = (Foo::RegisterFoo(), 0);
int bardummy = (Bar::RegisterBar(), 0);
int main() {
Factory::Instance()->CreateObject(0); // create foo object
Factory::Instance()->CreateObject(1); // create bar object
}
No, there is no way to inherit friend declaration from base class. However, if you make Base constructor private, instances of derived classes won't be possible to create without Factory help.
As others already said, friendship is not inheritable.
this looks like a good candidate of "Abstract Factory" pattern.
assume "SomeClass"es derived from base are used polymorphically.
declare a abstract factory base, which creates Base objects.
derive each concrete factory from base, override the base creation method...
see http://en.wikipedia.org/wiki/Abstract_factory_pattern for examples
You can't do that. This is done to protect encapsulation. See this post: Why does C++ not allow inherited friendship?
For future reference, another idea that came out of the chat between OP and me, which works with only one use of friend as the OP wanted. Of course, this is not a universal solution, but it may be useful in some cases.
Below code is a minimal one which shows the essential ideas. This needs to be "integrated" into the rest of the Factory code.
class Factory;
class Top { // dummy class accessible only to Factory
private:
Top() {}
friend class Factory;
};
class Base {
public:
// force all derived classes to accept a Top* during construction
Base(Top* top) {}
};
class One : public Base {
public:
One(Top* top) : Base(top) {}
};
class Factory {
Factory() {
Top top; // only Factory can create a Top object
One one(&top); // the same pointer could be reused for other objects
}
};
It is not possible. As others have said friendship is not inherited.
An alternative is to make all class hierarchy constructors protected and add the factory function/class as friend to all the classes you're interested in.