0

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.

2 Answers2

2

Whether or not some scope of your program is allowed to access functions and/or instantiate class types is decided by the compiler after overload resolution has been performed. That means available constructors are not "filtered" by their private or public visibility.

In your scenario, that might not make immediate sense when looking at the main function, from which you seem to instantiate objects of the class in question. But imagine you create an instance of the class from with a member function of that class: here, both private and public members are visible, and the compiler won't be able to decide which one it should take.

As a side note, if you don't want your class to be created by a default ctor, prefer to = delete it. Also, a default constructor and one with a defaulted single argument could certainly be refactored into two constructors, e.g. using in-class initializers.

lubgr
  • 37,368
  • 3
  • 66
  • 117
0

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;
};
srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25