2
enum class EmployeeType {Employee, Manager, Sales, Unknown};

class Employee
{
public:
    Employee() = delete;
    Employee(const Employee&) = delete;
    Employee& operator=(const Employee&) = delete;
    Employee& operator=(Employee&&) = delete;

    Employee(Employee&&) = default;

    explicit Employee(EmployeeType type);
}

When I write in main():

Employee e1(EmployeeType::Manager);

or

Employee e2(Employee(EmployeeType::Manager));

it works fine. When I write like this:

Employee e3({});
Employee e4(EmployeeType{});
Employee e5(EmployeeType(123));

compiler compiles it. But I want to forbid it using c++ keywords or using something else. I don't know how. I want to permit only this:

Employee e6(EmployeeType::Employee);
Employee e7(EmployeeType::Manager);
Employee e8(EmployeeType::Sales);
Employee e9(EmployeeType::Unknown);
Employee e10(Employee(EmployeeType::Employee));
Employee e11(Employee(EmployeeType::Manager));
Employee e12(Employee(EmployeeType::Sales));
Employee e13(Employee(EmployeeType::Unknown));

How can I do it?

I use g++ 5.4.0 in Ubuntu 16.04 LTS.

I write code in Qt Creator 4.1.0 with enabled C++11 in pro-file:

CONFIG += c++11

1 Answer 1

4

You can prevent Employee e3({}); by declaring an initializer_list constructor. This is always preferred when the initializer is a braced list:

Employee(std::initializer_list<int>) = delete;

The template type doesn't really matter.

However it is not possible to prevent a caller casting some value to EmployeeType and then providing that as constructor argument.

Sign up to request clarification or add additional context in comments.

3 Comments

What does assigning delete to a constuctor do?
@HSchmale it means there will be a compilation error if the code would have invoked that constructor
M.M, thank you, with initializer_list now it works well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.