Initialization of a class member with a parameterized constructor. Does the compiler believe that I declare a function?

I am trying to initialize a member of a class in which the member is an instance of another class. Visual Studio seems like I'm declaring a member of a function:

class OtherClass {
    OtherClass();
    OtherClass(string Foo);
}

class MainClass {
    // This Compiles. Default constructor used
    OtherClass Instance1;

    // Does not compile. Visual studio thinks I'm declaring a function member that returns an OtherClass. 
    OtherClass Instance2("Foobar");
}

I understand that I can accomplish what I want with a member initialization list, for example:

class MainClass {
    OtherClass Instance2;

    MainClass() : Instance2("Foobar") {}
}

I am simply confused by the fact that in the first example, the compiler understands that I initialize the NewClass member when I use the default constructor, but he thinks that I declare the function if I try to use the constructor that expects the string. Can someone explain the explanation for this and if there is another problem that I don't know about?

Update: This declaration ambiguity is named: Most Vexing Parse

+4
1

, { }.

:

OtherClass Instance2 = "Foobar";

OtherClass Instance2{ "Foobar" };
+4

Source: https://habr.com/ru/post/1687092/


All Articles