+ 8
Can we declare a constructor in private sector?
9 Réponses
+ 4
but then how it will be called??
+ 4
@Lakshay thanks..
+ 3
Yes you can.
+ 3
what's Singleton pattern ??
+ 3
someone plz explain how can we call a constructor declared privately & is there any use of doing so?
I'm not able to understand the link above posted by Chessmaster.
Do explain using simple terms...
+ 2
This StackOverflow thread explains it all I hope:
https://stackoverflow.com/questions/4648602/private-constructor
+ 2
When constructor & destructor are public, they are called automatically.
If we declare them as private we have to call them explicitly.
Here is program to use a privately declared constructor :
class X
{
private :
int a;
X(){
a = 11;
cout<<"\n This is contr";}
~X(){
cout<<"\n This is destr";}
public:
void func()
{
this->X::X(); //invoke constructor
cout<<"\n a = "<<a;
this->X::~X(); //invoke destructor
}
};
void main()
{
X*x; // x is a pointer to class X
x->func; // x invokes func
}
In this code func() which is public member of class invokes constructor and destructor from private section of class indirectly.
Output:
This is contr
a = 11
This is destr
+ 1
Yes we can, but it would not be much useful then ...
+ 1
yes we can declare a constructor in private but in some books and sites it is writen wrong that we can't write