I ran into some code and it sorta confused me. I was under the assumption that if you did not provide a constructor, one will be provided for you. also, if you provide a constructor the default constructor will not be used and be hidden. keeping that in mind, why would someone write something like the code below. They wrote a default constructor in the private section of the code but used another constructor in the public section. isnt the default constructor hidden by default anyway. why put something thats hidden already in the private section. what does that do..they still provide a constructor so its not like they were trying to prevent the class from being instantiated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class example
{
example(){}
public:
example(int x, int y, int z) : mx(x),my(y),mz(z) {}
private:
int mx;
int my;
int mz;
};
In this example, the class writer wanted an explicit constructor to be called. By hiding the default, the class writer is guarenteed that only the explicit constructor will be called.
Also, when a default constructor is provided by the compiler, it is not hidden: otherwise, how could your class users construct the object?
No, I'm saying in this example the class writer only wants the public constructor to be called. If the programmer using this class tries to construct this class in any other way, the compiler will not allow it, thereby granting the class writer what was designed.
If you make a default constructor public, a programmer can call it. If you make it hidden, a programmer can not.
you cant call a default constructor (the one provided to you) if you provide a constructor of your own. so how could they call it. im not understanding i guess. in other words
class test
{
public:
test(int amount){}
};
class test2
{
test2(){}
public:
test2(int amount){}
};
// same result regardless if provided default constructor is private
int main(int argc, char *argv[])
{
test ts; // not possible
test2 ts2; // not possible
}
A default constructor is one that need not take an argument. If you do not provide one the compiler will generate one. So providing a private default constructor prevents the compiler from generating a public one automatically.
Is that all the code there is?
A private constructor could be used by methods and friends, if there are any.
If it was protected, instead of private, it could be used by a child.
Though as it is, I too see no use for it.