Search code examples
c++constructor

Why can I initialize a class/struct with a scalar value?


I came across this behavior today and I can't find a reason for why it's working.

Non-working code

struct MyStruct {
    int x;
    int y;
};

MyStruct foo = 1;
error: conversion from ‘int’ to non-scalar type ‘MyStruct’ requested

Working code

struct MyStruct {
    int x;
    int y;
    MyStruct(int x) : x(x) {
        //
    }
};


MyStruct foo = 1;

Question

Why does C++ know how to use this constructor? Shouldn't it still be having a compiler error saying that I can't assign an int to a struct? Why don't I need MyStruct foo = MyStruct(1);?

Online GDB link to code


Solution

  • Thanks to everyone for the comments and answers, but the best response came from @273K in a comment.

    The question demonstrates a Converting Constructor. From the link,

    A converting constructor specifies an implicit conversion from the types of its arguments (if any) to the type of its class.

    I created a constructor with a single int argument. This creates an implicit conversion from int to MyStruct.

    As others mentioned, when writing MyStruct foo = 1;, that's actually declaring and initializing an instance of MyStruct. During the (copy) initialization, the compiler will be able to find that implicit conversion from int to MyStruct and call the converting constructor as part of the process.