lundi 29 juillet 2019

Should the deleted default constructor be in Public or Private?

I had to delete the default constructor to ensure that the parameterized constuctor is used always. That's when I wanted to know if my deleted default constructor should be under public or private access specifier.

I just wrote a sample code to test this. I tried to access the deleted default constructor.

class A
{
public:
    A(const int val)
    {
        assign = val;
    }
private:
    A() = delete;
    int assign;
};

int main()
{
    A obj1(5);
    A obj2;
}

main.cpp: In function ‘int main()’:

main.cpp:35:7: error: ‘A::A()’ is private within this context

A obj2;

main.cpp:28:5: note: declared private here

A() = delete;

main.cpp:35:7: error: use of deleted function ‘A::A()’

A obj2;

main.cpp:28:5: note: declared here

A() = delete;

Aucun commentaire:

Enregistrer un commentaire