Search code examples
c++c++11coding-style

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;


Solution

    • You don't need to use the deleted ctor.
    class A
    {
    public:
        A(const int &val) : assign(val){}
    private:
        int assign;
    };
    int main()
    {
        A a;
        return 0;
    }
    

    gives error: no matching function for call to ‘A::A()’

    and

    class A
    {
    public:
        A() = delete;
        A(const int &val) : assign(val){}
    private:
        int assign;
    };
    int main()
    {
        A a;
        return 0;
    }
    

    gives error: use of deleted function ‘A::A()’

    • Concerning the use of delete, it could be useful with inheritance.
    class A
    {
    public:
        A() : assign(0){}
        A(int val) : assign(val){}
    private:
        int assign;
    };
    
    class B : public A
    {
    public:
        B() = delete;
        B(int val) : A(val){};
    };
    
    class C : public A
    {
    
    };
    
    class D : public A
    {
    public:
        D() = delete;
    };
    
    
    int main()
    {
        A a1; //works
        A a2(5); //works
    
        //B b1; -- does not work : error: use of deleted function ‘B::B()’
        B b2(3); //works
    
        C c1; //works, creates a default ctor
        //C c2(7); -- does not work : no matching function for call to ‘C::C(int)’
    
        //D d1; -- does not work :error: use of deleted function ‘D::D()’
        //D d2(2); -- does not work: error: no matching function for call to ‘D::D(int)’
        return 0;
    }
    

    Note that D can't be instantiated. Quite useless though :)