-3

in following code: `

#include <iostream>

struct MyStruct {
  int i = 1;
};
int main() {
  MyStruct(some); // some is actually a variable name, it compiles, is it in the
                  // c++ standard?
  std::cout << some.i << std::endl;
}

`

why can i initialzie MyStruct(some)? above code compiles and runs

shan
  • 176
  • 8
  • The second example doesn't work because now your class doesn't have a default constructor anymore. See [when default ctor is synthesized](https://stackoverflow.com/questions/9635772/is-it-true-that-a-default-constructor-is-synthesized-for-every-class-that-does-n) – Jason Nov 19 '22 at 05:35

2 Answers2

0

I doubt that the variable "some" in the first code is a variable, it wouldn't run when I try to declare a variable called some. But your problem with this code...

struct MyStruct {
    MyStruct(const int &value) {}
};

int main() {
    std::string(s2);
    MyStruct(some); // illegal now 
    std::cout << s2 << std::endl;
}

is that you don't have an identifier for the MyStruct that you are instantiating.

struct MyStruct {
    MyStruct(const int &value) {}
};

int main() {
    int some = 5;
    std::string(s2);
    MyStruct myStruct (some); // illegal now 
    std::cout << s2 << std::endl;
}

Here I placed "myStruct" as the identifier for the "MyStruct". I also declared a variable called "some" to check if it runs that way, which it does.

m3ow
  • 151
  • 7
  • i edit my question to make it more clear, `some` is a variable, it compiles and run. my question is the form of declaration is werid for me, is it a convention or something? – shan Nov 19 '22 at 06:23
0

The way of declaring and defining a variable is very wired. If you want to define std::string and MyStruct, you are supposed to use the following way: std::string s2("initialized value"); MyStruct some. In your second case, MyStruct has defined a constructor so the default constructor in the first case doesn't exist anymore unless you explicitly define it.
So in the second case, if you want to initialize an instance with one argument, the following is a supported way:MyStruct some(10);. This statements call the constructor you write.

Virux
  • 138
  • 9
  • the wiredness is actully my question, is this way the allowed way? i happens to find it compiles during a unit test, which lead to a wrong testing result – shan Nov 19 '22 at 06:24
  • I don't think it is a good way to define a variable. Such code is actually very confusing so you would better not use it. Instead, just write the code in the style that I recommend in my answer. – Virux Nov 19 '22 at 06:31