c++c++11

Dont allow use of default constructor in C++


I'm trying to create a class in C++ which forbids the use of the default constructor.
Nevertheless, I think I'm failing, or I'm not understanding what is happening behind the scenes. Here is what I have so far:

class Point {
public:
        float x;
        float y;
        Point(float newX, float newY); //Definition is irrelevant
        Point() = delete; //Default or "empty" constructor is forbidden, so deleted
}
/* ... */
int main(void)
{
        Point a(1, 2); //Ok, should be available
        Point b; //Ok, does not compile
        Point c(); //Not ok, it does compile :(
}

My intended behavior is for point c not to compile. I'd appreciate help in generating such a behavior, or if not possible, an explanation of why this works like that.

Thank you in advance


Solution

  • What is happening is a vexing parse. You're not declaring an object, but a function with name c and return type of class Point.


    Declaring any constructor will prevent compiler from generating default constructor, so declaration with =delete is superfluous.


    Aggregate initialization

    If you know the order, you don't even need constructor:

    Point p{newX, newY};
    

    Will work just fine.


    Uniform initialization syntax

    In the future, to avoid such cases, use {}:

    Point p{}; //default constructs