The following code:
#include <iostream>
using namespace std;
class Myclass
{
private:
Myclass ();
public:
int num;
};
int main()
{
Myclass foo();
return 0;
}
Compiles without any warnings or errors in Eclipse.
However
#include <iostream>
using namespace std;
class Myclass
{
private:
Myclass ();
public:
int num;
};
int main()
{
Myclass foo;
return 0;
}
Gives me this error: error: 'Myclass::Myclass()' is private within this context
Why does foo give me this error while foo() doesn’t?
Is foo() being mistaken as a function or does date_type name() have a special meaning?
>Solution :
Why can MyClass foo() access private default constructor?
It cannot (fancy hacks that allow you to call a private constructor aside).
Is foo() being mistaken as a function
Myclass foo(); is a function declaration. The mistake is to expect it to be something else. To call the constructor write:
Myclass foo; // or
Myclass foo{};
As this mistake is rather common, compilers typically warn about it. Don’t ignore warnings, and crank up the warning level when there was no message for your code.