My question is about constructors in OOP(C++). When I define default constructor in a class as private and when I initialize an object of that class in main as default then error occurs that default constructor is inaccessible. It's fine. But then I also make default argument constructor in Public section and when I initialize object in main again then ambiguous call to function overloading occurs. So my question is that if private constructor is not accessible from main then compiler should call the constructor in public section which is default argument constructor. Kindly answer why is this happening.
For Example take a class
#include "iostream"
class Type
{
private:
Type()
{
std::cout<<"Private Default";
}
public:
Type()
{
std::cout<<"Public Default";
}
};
int main()
{
Type obj;
}
Here both default constructor is in scope Type::Type()
You can't overload like this i.e there is no private scope or public scope all are in Type
scope So you can't overload this according to c++ overloading rules.
Output for above code:
main.cpp:11:5: error: ‘Type::Type()’ cannot be overloaded
Type()
^~~~
main.cpp:6:5: error: with ‘Type::Type()’
Type()
^~~~
main.cpp: In function ‘int main()’:
main.cpp:19:10: error: ‘Type::Type()’ is private within this context
Type obj;
^~~
main.cpp:6:5: note: declared private here
Type()
^~~~
And if you comfort with c++11
you can delete constructor like
class Type
{
public:
Type() = delete;
};