Why cant we create Object if constructor is in private section? - c++

I want to know why cant we create object if the constructor is in private section. I know that if i make a method static i can call that method using
<classname> :: <methodname(...)>;
But why can't we create object is what I don't understand.
I also know if my method is not static then also I can call function by the following:
class A
{
A();
public:
void fun1();
void fun2();
void fun3();
};
int main()
{
A *obj =(A*)malloc(sizeof(A));
//Here we can't use new A() because constructor is in private
//but we can use malloc with it, but it will not call the constructor
//and hence it is harmful because object may not be in usable state.
obj->fun1();
obj->fun2();
obj->fun3();
}
So, my question is: why can't we create an object when constructor is private?

Because it is not accessible to the program, that's what private means. If you declared a member function or variable private, you would not be able to access them either. Creating private constructors is actually a useful technique in C++, as it allows you to say that only specific classes can create instances of the type. For example:
class A {
A() {} // private ctor
friend class B;
};
class B {
public:
A * MakeA() {
return new A;
}
};
Only B can create A objects - this is useful when implementing the factory pattern.

A constructor is a special member function. It obeys the same rules as any other method when it comes to accessing it. The private access label prevents class users from invoking/accessing members declared under it.

The "new" operator needs to call the constructor, so if the constructor is private you can not execute the code "obj = new A" except inside member functions of the class A itself.
I would guess that what you have encountered is a technique that is very often used in Java (and yes I know you're writing C++, but the principle is the same) where the designer of the class wants to make sure that one and only one instance of this class will ever exist (which is called a "singleton"). To achieve this, he needs to prevent other code from creating further instances of the class using new, and making the constructor private is one way to do that. Here's a piece of Java code illustrating the technique.
public class MySingleton {
private MySingleton() {
// Private constructor, to prevent instantiation using "new"
// outside of this class.
}
public synchronized static MySingleton getInstance() {
static MySingleton instance = null;
if (instance == null) {
// I can use new here because I'm inside the class.
instance = new MySingleton();
}
return instance;
}
}
Even if you don't know Java, the syntax is similar enough to C++ that you should understand what this code is doing. The point is that the only way to get a reference to an instance of the MySingleton class elsewhere in the code is to call the static class member getInstance().
MySingleton obj = MySingleton.getInstance();

You can't instantiate your class because the constructor is private. private member variables and functions cannot be used outside of the class itself.
If you want to be able to instantiate your class, you have two options.
Option 1 is to make the constructor. This is the Right Thing to do in the vast majority of cases. Making a constructor private is a useful technique, but only when trying to accomplish specific goals.
Option 2 is to create a public static factory method. You would typically do this when Option 1 isn't an option.
class A
{
A();
public:
static A* Create() { return new A; }
void fun1();
void fun2();
void fun3();
};
int main()
{
A *obj = A::Create();
//Here we can't use new A() because constructor is in private
//but we can use malloc with it, but it will not call the constructor
//and hence it is harmful because object may not be in usable state.
obj->fun1();
obj->fun2();
obj->fun3();
}

Related

Static initialization with private constructor

In a class I have a static member that represents the singleton instance of that class:
class A {
public:
static const std::shared_ptr<A> INSTANCE;
private:
A();
};
In order to prevent more instances I made the constructor private. Now I have trouble to initialize the static var, because the initializer cannot access a private member. Here's the code I use in the .cpp file:
const std::shared_ptr<A> A::INSTANCE = std::make_shared<A>();
A factory method wouldn't help either, as it would have to be public as well. What else can I do to make this work? Note: I'd like to avoid the typical static get() method if possible.
You can't use make_shared, but you can just create the instance directly:
const std::shared_ptr<A> A::INSTANCE { new A };
The initialization of a static member is unrelated to the constructor, so the global statement is indeed the right way to go. Is it not working for you?
EDIT: I just realized you're trying to avoid using a singleton access method for some reason. Sounds suspiciously like the Borg pattern. :) Unrelated to you r specific question but I'd advise you to reconsider.

Accessing private C++ methods within C++/CLI wrapper

Given a class method in C++ that has to be private there, how to make C++/CLI access it. Example: C++ class has a private constructor that shouldn't be exposed to the external user, C++/CLI managed code has to have similar private constructor, but internally it must access private C++ constructor to instantiate a member pointer referring to C++ native class.
Keep in mind, first of all, the goal of making things inaccessible (i.e. private) generally contradicts the goal of making things accessible. If you're able to change the class declaration, then you have some options. I don't know the specifics of your C++/CLI requirements, but perhaps one of these options will give you what you need.
Protected and Inheritance
To an "outsider", private and protected members are equally inaccessible. But to a subclass, private is still private while protected members are accessible. You can gain access to protected members by subclassing. This can be one way to unit test "private" members of a class without fully exposing it to the world.
class A {
protected: // was private
int sum(int a, int b);
};
class TestA : public A {
public:
bool testSum(int expected, int a, int b) {
return expected == sum(a, b);
}
};
So access to protected method sum in class A becomes accessible by making it protected and subclassing. The private member will remain inaccessible to everything else except subclasses.
Static Factory Method
You mentioned a private constructor; if you are needing to manage construction, you might accomplish that with a static factory method. For instance:
class Foobar {
private:
Foobar() { } // Don't let anyone just make one.
public:
static Foobar* Create() { return new Foobar; }
};
// To create a Foobar instance:
Foobar* pfoo = Foobar::Create();
This is not the best interface (better to use a shared_ptr, for instance), but it demonstrates my meaning. Note that since the factory function Create is public, anyone can create one. However, you can change the body of Create to something more complex: include bookkeeping, initialization, etc. The factory method is a way to manage creation, not restrict it. Granted, you may not want this, but it's an option if you need to manage construction.
Friends
C++ permits giving access of the private parts of classes to other classes/functions via the friend keyword.
class A {
int x; //private
friend class B;
};
class B {
void foobar(A& a) {
a.x = 42; // permissible, because A declared class B a friend
}
};
Friendship can be granted to another class or to a function. This can easily break encapsulation and make code difficult to follow or keep safe, but it also gives you the means to expose private members to exactly just those who need it.

Method calling a the static singleton instance to call another method

I'm browsing some random code and I found some confusing method, the class is a singleton,
class CFoo
{
CFoo* _instance;
CFoo(){};
public:
~CFoo(){};
static CFoo* getInstance()
{
if(!_instance)
_instance = new CFoo;
return _instance;
}
static void deleteInstance()
{
if(_instance)
delete _instance;
}
// just ordinary member method.
void FooMethod()
{
CFoo::getInstance()->BarMethod(); //confusing..
}
// just ordinary member method.
void BarMethod()
{
//code here..
}
};
CFoo* CFoo::_instance = NULL;
Why FooMethod have to call the CFoo::getInstance() to call the BarMethod? Why not just calling BarMethod() directly?
Please advise.
If you call CFoo::getInstance()->BarMethod() within CFoo::FooMethod(), then the this keyword in the BarMethod refers to CFoo::_instance.
If you call BarMethod() within CFoo::FooMethod(), then the this keyword in the BarMethod refers to the same object on which FooMethod() was called.
It is not entirely clear whether there is effectively any difference. On the one hand, the only constructor that you implemented is private and you refer to the class as a Singleton. This supports the fact that only one instance of CFoo should exist, i.e. this == CFoo::_instance should always hold within BarMethod. On the other hand, CFoo has a public copy constructor, so this == CFoo::_instance might not always be true within BarMethod.
You could call the FooMethod and the Barmethod directly if you could create an object of this class. the problem is you can't do it because the construtor is private. the only way you can create the instance is using the getInstance method. and the method ensure it had no more than single object of this class.
That's why it called singleton.

Use of public destructor when the constructor is private

I have seen code where the constructor has been declared as private while the destructor is public. What is the use of such a declaration? Is the destructor required to be public so that during inheritance the calls can be possible or is it a bug in the code?
The question might seem to be a bit short on information, but what I really want to know is if having a public destructor when the constructor is required to be private abides by the C++ rules?
Short Answer
Creating a constructor as private but the destructor as public has many practical uses.
You can use this paradigm to:
Enforcing reference counting (See Hitesh Vaghani's example).
Implement the singleton pattern
Implement the factory pattern.
Long Answer
Above I hinted that you can use private constructors and destructors to implement several design patterns. Well, here's how...
Reference Counting
Using private destructor within an object lends itself to a reference counting system. This lets the developer have stronger control of an objects lifetime.
class MyReferenceObject
{
public:
static MyReferenceObject* Create()
{
return new MyReferenceObject();
}
void retain()
{
m_ref_count++;
}
void release()
{
m_ref_count--;
if (m_ref_count <= 0)
{
// Perform any resource/sub object cleanup.
// Delete myself.
delete this; // Dangerous example but demonstrates the principle.
}
}
private:
int m_ref_count;
MyReferenceObject()
{
m_ref_count = 1;
}
~MyReferenceObject() { }
}
int main()
{
new MyReferenceObject(); // Illegal.
MyReferenceObject object; // Illegal, cannot be made on stack as destructor is private.
MyReferenceObject* object = MyReferenceObject::Create(); // Creates a new instance of 'MyReferenceObject' with reference count.
object->retain(); // Reference count of 2.
object->release(); // Reference count of 1.
object->release(); // Reference count of 0, object deletes itself from the heap.
}
This demonstrates how an object can manage itself and prevent developers from corrupting the memory system. Note that this is a dangerous example as MyReferenceObject deletes itself, see here for a list of things to consider when doing this.
Singleton
A major advantage to private constructors and destructors within a singleton class is that enforces the user to use it in only the manner that the code was design. A rogue singleton object can't be created (because it's enforced at compile time) and the user can't delete the singleton instance (again, enforced at compile time).
For example:
class MySingleton
{
public:
MySingleton* Instance()
{
static MySingleton* instance = NULL;
if (!instance)
{
instance = new MySingleton();
}
return instance;
}
private:
MySingleton() { }
~MySingleton() { }
}
int main()
{
new MySingleton(); // Illegal
delete MySingleton::Instance(); // Illegal.
}
See how it is almost impossible for the code to be misused. The proper use of the MySingleton is enforce at compile time, thus ensuring that developers must use MySingleton as intended.
Factory
Using private constructors within the factory design pattern is an important mechanism to enforce the use of only the factory to create objects.
For example:
class MyFactoryObject
{
public:
protected:
friend class MyFactory; // Allows the object factory to create instances of MyFactoryObject
MyFactoryObject() {} // Can only be created by itself or a friend class (MyFactory).
}
class MyFactory
{
public:
static MyFactoryObject* MakeObject()
{
// You can perform any MyFactoryObject specific initialisation here and it will carry through to wherever the factory method is invoked.
return new MyFactoryObject();
}
}
int main()
{
new MyFactoryObject(); // Illegal.
MyFactory::MakeObject(); // Legal, enforces the developer to make MyFactoryObject only through MyFactory.
}
This is powerful as it hides the creation of MyFactoryObject from the developer. You can use the factory method to perform any initilisation for MyFactoryObject (eg: setting a GUID, registering into a DB) and anywhere the factory method is used, that initilisation code will also take place.
Summary
This is just a few examples of how you can use private constructors and destructors to enforce the correct use of your API. If you want to get tricky, you can combine all these design patterns as well ;)
First thing: the destructor can be private.
having a public destructor when the constructor is required to be
private abides by the C++ rules?
It's totally working in C++. In fact, a great example of this scenario is the singleton pattern, where the constructor is private and the destructor is public.
In reverse order.
Is the destructor required to be public so that during inheritance the calls can be possible or is it a bug in the code?
Actually, for inheritance to work the destructor should be at least protected. If you inherit from a class with a private destructor, then no destructor can be generated for the derived class, which actually prevents instantiation (you can still use static methods and attributes).
What is the use of such declaration?
Note that even though the constructor is private, without further indication the class has a (default generated) public copy constructor and copy assignment operator. This pattern occurs frequently with:
the named constructor idiom
a factory
Example of named constructor idiom:
class Angle {
public:
static Angle FromDegrees(double d);
static Angle FromRadian(double d);
private:
Angle(double x): _value(x) {}
double _value;
};
Because it is ambiguous whether x should be precised in degrees or radians (or whatever), the constructor is made private and named method are provided. This way, usage makes units obvious:
Angle a = Angle::FromDegrees(360);
You make constructor private if you want to prevent creating more then one instance of your class. That way you control the creation of intances not their destruction. Thus, the destructor may be public.
One example in my head, let's say you want to limit the class instance number to be 0 or 1.
For example, for some singleton class, you want the application can temprary destroy the object to rducue memory usage. to implement this constructor will be private, but destructor will be public. see following code snippet.
class SingletoneBigMemoryConsumer
{
private:
SingletoneBigMemoryConsumer()
{
// Allocate a lot of resource here.
}
public:
static SingletoneBigMemoryConsumer* getInstance()
{
if (instance != NULL)
return instance;
else
return new SingletoneBigMemoryConsumer();
}
~SingletoneBigMemoryConsumer()
{
// release the allocated resource.
instance = NULL;
}
private:
// data memeber.
static SingletoneBigMemoryConsumer* instance;
}
//Usage.
SingletoneBigMemoryConsumer* obj = SingletoneBigMemoryConsumer::getInstance();
// You cannot create more SingletoneBigMemoryConsumer here.
// After 1 seconds usage, delete it to reduce memory usage.
delete obj;
// You can create an new one when needed later
The owner of an object needs access to the destructor to destroy it. If the constuctors are private, there must be some accessible function to create an object. If that function transferes the ownership of the constructed object to the caller ( for example return a pointer to a object on the free store ) the caller must have the right to access the destructor when he decides to delete the object.

c++ special method visibility

I have a simple object, of type "ObjectX", with a simple method called "doSomething()". I'd like to make doSomething ONLY accessable by other ObjectX's. In other words, if something that is either static, or not an object of type "ObjectX" tries to call doSomething, it will be unable to. However, if an object of type ObjectX tries to call the method, it WILL be able to.
This differs from a private method, in that, a private method can only be called from the same object it is in. If there were another object of the same type calling that method on a different object, it would be locked out.
private does almost exactly what you want. Only objects of the same type can use private methods, and other objects can call those functions on other objects (that is, private functions are not restricted to the invoking object).
The only thing that is not as you described is that that static functions in the same class can also use private functions. There is no language feature that lets you restrict a function to the object only (excluding static functions).
I don't know where you get your facts. A private function A::foo can be called by any object of type A. Be it on itself or on another instance.
class A
{
public:
void foo(const A& other) { other.priv(); }
private:
void priv() const {}
};
int main()
{
A a1, a2;
a1.foo(a2);
return 0;
}
In C++
Class A{
A a;
doSomething(){
a.doSomething();
}
}
The above code would work.And this is the reason copy constructor work.
Class B{
A a;
doSomethingElse(){
a.doSomething();
}
}
Above would not anyways work.
If you want to provide access to B as well make A a friend of B by specifying friend B; in class A.