I am currently studying the design patterns described by the Gang of Four. The Composite Pattern, is what I am currently trying to concertize mentally. While doing this I was looking at an example of its implementation shown here. If you notice in the portion were they are implementing the leaf classes of this pattern they place a generic version of the classes" constructor in private and they place an overloaded version of the constructor in public. Trying to figure this out on my own I came across a forum post that describes the various reasons one might place the constructor in private here by Kerido. Of those 5 examples I am certain its not B or E. But out of A,C, and D I am not sure. I place portions of the code I am talking about to reduce having to hunt through the posted link above. Also the explanations of A, C, and D (reasons to have a constructor in private) I'll past below the class in question.
/*
* Capacitor is a LEAF class which is directly inherited from the -
* ElectronicComponet class.
*/
class Capacitor:public ElectronicComponent
{
float capacitance_muF; //Capacitance value in micro fared.
Capacitor(){} // Point in question. Why are they doing this, in this context?
public:
/*
* Constructor - initialize the capacitance value.
*/
Capacitor(float muF)
:capacitance_muF(muF)
{
}
/*
* Prints the Capacitor's specification.
*/
void PrintSpec(ostream& ostr, string prefix = "")
{
ostr<<prefix<<"Capacitor ("<< capacitance_muF <<" muF )"<<endl;
}
/*
* Performs the Capacitor's real function of modifying input Voltage & Current.
* Electrical engineers, please help :)
* Now I just put a printing of Voltage and current as place holder.
*/
void DoFunction(float& voltage, float& current)
{
cout<<endl<<"Capacitor Input ("<<voltage<<" V ,"<<current<<" Amp)
Capacitance ="<< capacitance_muF<<endl;
}
};
A. Your class instances are created in a static method. The static method is then declared as public.
class MyClass()
{
private:
MyClass() { }
public:
static MyClass * CreateInstance() { return new MyClass(); }
};
C. (Only applies to the upcoming C++0x standard) You have several constructors. Some of them are declared public, others private. For reducing code size, public constructors 'call' private constructors which in turn do all the work. Your public constructors are thus called delegating constructors:
class MyClass
{
public:
MyClass() : MyClass(2010, 1, 1) { }
private:
MyClass(int theYear, int theMonth, int theDay) { /* do real work */ }
};
D. You want to limit object copying (for example, because of using a shared resource):
class MyClass
{
SharedResource * myResource;
private:
MyClass(const MyClass & theOriginal) { }
};
Any thoughts on the matter would be nice thanks