Search code examples
c++constructordefault-constructor

Is there any case where a class with deleted ctor could be useful?


I wonder why the standard allows this kind of declaration.

class A
{
public:
    A() : bar(0){}
    A(int foo) : bar(foo){}
private:
    int bar;
};

class B : public A
{
public:
    B() = delete;
};

B can't be instantiated.

  B b1; //error: use of deleted function ‘B::B()’
  B b2(2); //error: no matching function for call to ‘B::B(int)’

still true with

class A
{
public:
    A() : bar(0){}
private:
    int bar;
};

class B : public A
{
public:
    B() = delete;
};

which gives

B b1; //error: use of deleted function ‘B::B()’

note: this is different with not having a default ctor:

class G
{
protected:
    int assign;
};

class H : public G
{
public:
    H() = delete;
};

gives

G g1; //works
//H h1; -- error: use of deleted function ‘H::H()’

Is there any case where this can be useful?


Solution

  • Is there any case where a class with deleted ctor could be useful?

    Classes can be used without creating instances. Most typical examples of such classes are type traits: All features of for example std::is_same and std::numeric_limits can be used without creating an instance. As such, their constructor could be deleted without losing any functionality.

    That said, it is typically not necessary to delete the constructor of such classes, and in fact the implicit contsructors of standard type traits are not deleted. Deletion of constructors is typically used to remove only certain constructors, rather than all of them. To be clear: Just because something isn't typical, doesn't mean that it should be an error.