Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If I declare a constructor as private can I call this constructor in another class?

class A{

private A(){

...
}


class B {

A  a_obj=new A(){}           //shows an error--not visible 

}


I want to declare a private constructor anyhow, I can't violate that, but still can I use it in other way around?
Posted
Updated 16-Feb-11 21:39pm
v3
Comments
Dalek Dave 17-Feb-11 3:39am    
Edited for Grammar.

You cannot initialize a object using private constructor.

Please see this[^]
 
Share this answer
 
Comments
Dalek Dave 17-Feb-11 3:39am    
Good Link.
Venkatesh Mookkan 17-Feb-11 3:41am    
Thanks DD
Not only you cannot instantiate a class with all constructors private (not from outside of the class, but class can provide a factory creating an instance), but this is also a well known method of programming.

In particular, this is the only way to created functionality of abstract classes (there is no "abstract" keyword in C++, in contrast to newer OOP languages). Such classes are very useful it a class hierarchy needs a common base class with common functionality which can only be used as a base class; an accidental attempt to create an instance of such class with be prevented by compiler.

—SA
 
Share this answer
 
Comments
Manfred Rudolf Bihy 17-Feb-11 5:00am    
Good answer! 5+
Sergey Alexandrovich Kryukov 17-Feb-11 20:07pm    
Thank you.
--SA
Espen Harlinn 17-Feb-11 9:26am    
Factory methods are a well-known pattern, my 5.

Abstract methods in c++ are called pure virtual functions.
class Abstract {
public:
virtual void pure_virtual() = 0;
};
Sergey Alexandrovich Kryukov 17-Feb-11 20:07pm    
Thank you for the note, I should have mentioned that in my Answer.
The thing is: it does not make whole class abstract (and in C# would not compile).
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900