Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can MyClass foo() access private default constructor?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading