Trollliar
Trollliar

Reputation: 866

Forbid using default constructor in derived classes, C++

Is there any way to create base class (such as boost::noncopyable) and inherit from it, which will forbid compiler to generate default constructor for derived classes, if it wasn't made by user (developer)?

Example:

class SuperDad {
XXX:
  SuperDad(); // = delete?
};

class Child : YYY SuperDad {
public:
  Child(int a) {...}
};

And result:

int main () {
  Child a;     // compile error
  Child b[7];  // compile error
  Child c(13); // OK
}

Upvotes: 8

Views: 2664

Answers (3)

Tomasz Sodzawiczny
Tomasz Sodzawiczny

Reputation: 347

According to this cppreference.com article (which is basically a lawyer-to-human translation of C++ standard 12.1. section):

If no user-defined constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

The only way you can control the implicitly defined constructor of Child from SuperDad is making the compiler to define it as deleted.

You can do that by making the default constructor (or destructor) of SuperDad deleted, ambiguous or inaccessible - but then you have to define some other way to create the base class and use it implicitly from all the child constructors.

Upvotes: 1

RAEC
RAEC

Reputation: 332

#include <iostream>
using namespace std;


class InterfaceA
{
public:

InterfaceA(std::string message)
{
    std::cout << "Message from InterfaceA: " << message << std::endl;
}

private:
    InterfaceA() = delete;
};


class MyClass: InterfaceA
{
public:
    MyClass(std::string msg) : InterfaceA(msg)
    {
        std::cout << "Message from MyClass: " << msg << std::endl;
    }
};

int main()
{
    MyClass c("Hello Stack Overflow");
    return 0;
}

Upvotes: 4

Trollliar
Trollliar

Reputation: 866

Make the constructor private.

protected:
    Base() = default;

Upvotes: 7

Related Questions