How to invoke a function in a class which is having private constructor. Eg: Code: class A { private A(){} public void fun(int a ) { ................... ................. } }; In this example if we want to invoke fun(int), how can we do that?
Exactly as you would invoke a public function of a class with a non-private constructor, i.e. Code: A* foo = whatever(); // this function returns a pointer to an object of class A foo.fun(0); // this invokes A::fun(int). Of course, if the code you posted is all the code you have, then the answer is that you can't, because you have no way of constructing an object of class A.
Thank you xpi0t0s for your responce. But I am sorry that I posted in a wrong forum.. I got this doubt when I am using c#. I will start a new thread in C# as well. Still I would like to know how this will happen in C++ as well.. Is it mandatory in C++ that a class should have at least one public or protected constructor..
Thought of adding more details regarding the scenario I faced in C#, where as in C++ I would like to know more about private constructors, because of that I opened a new thread in C#.Since that thread is closed I am adding here itself. I am using .Net Compact framework. I am trying to develop Sticky Notes Application in which a particular note can be send as an SMS or E-Mail to the selected users. To send an E-MAil I need to use EmailAccount class. This class is not having any constructors. But there is a function send() which can be used to send the EMailMessage. send() is a non-static function. So I am not getting how to invoke this function.
But what will happen when you will call whatever(). this function should return object of A class only..again u have to call private constructor.. Can you give proper code???
For my problem using OutlookSession.EmailAcounts we can send email.. I have to know more about API to use them Regarding private constructors in C++ If the code is like Code: class A { private A() {} public fun() { ........... } static A& create() { A *a = new A(); return *a; } }; To create an object for A. Code: A &b = A::create(); In this way we can control the number of objects that are getting created for a class. Please see http://www.velocityreviews.com/forums/t279993-private-constructor.html
This works (displays 3) in Visual Studio 2008: Code: class A { private: A(){} public: int foo(){return 3;} friend A* whatever(); }; A* whatever() { return new A; } int _tmain(int argc, _TCHAR* argv[]) { A* baz=whatever(); printf("%d\n",baz->foo()); return 0; } I would expect C# to be identical to the above apart from maybe the odd bit of syntax. With a private constructor you have to have either a member function that returns a new object such as the create() function previously or a friend that will create one for you.