+ 8

Can we declare a constructor in private sector?

24th Jul 2017, 8:32 AM
Himani
9 Réponses
+ 4
but then how it will be called??
24th Jul 2017, 11:02 AM
Himani
+ 4
@Lakshay thanks..
29th Jul 2017, 8:14 PM
Himani
+ 3
Yes you can.
24th Jul 2017, 8:58 AM
ChessMaster
ChessMaster - avatar
+ 3
what's Singleton pattern ??
24th Jul 2017, 12:39 PM
Himani
+ 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...
24th Jul 2017, 4:59 PM
Himani
+ 2
This StackOverflow thread explains it all I hope: https://stackoverflow.com/questions/4648602/private-constructor
24th Jul 2017, 11:09 AM
ChessMaster
ChessMaster - avatar
+ 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
26th Jul 2017, 2:55 AM
Lakshay
Lakshay - avatar
+ 1
Yes we can, but it would not be much useful then ...
24th Jul 2017, 1:43 PM
Lakshay
Lakshay - avatar
+ 1
yes we can declare a constructor in private but in some books and sites it is writen wrong that we can't write
24th Jul 2017, 3:39 PM
DISHA Rajput
DISHA Rajput - avatar