Is there are different between List x; and List x(); in C++

Dani AI

Generated

A brief, practical clarification tied to the original posts.

asked whether List x; and List x(); are different. pointed toward a parsing difference; the following explains that difference more fully and shows safer, modern forms to use.

struct List { List(); /* ... */ };

List a;        // declares a variable 'a' of type List (default-constructs)
List b();      // declares a function 'b' that returns List (no parameters)
List c{};      // C++11 list-initialization: unambiguously declares an object
List d = List(); // value-initializes an object (works in pre-C++11 code)

The middle line above is the classic "most vexing parse": what looks like a default construction can be parsed as a function declaration. For built-in types the effect is still surprising: int i; leaves i uninitialized (if local), while int i(); is a function declaration. To avoid ambiguity and accidental uninitialized variables in modern code prefer brace initialization (List x{}) or explicit copy/value initialization (List x = List()), and avoid the form Type x(); unless a function prototype is intended.

Authoritative references:

List (uniform) initialization

Note: this thread is old as commented; the above advice reflects C++11 and later practices but also gives safe patterns for older C++98 code.

Recommended Answers

All 2 Replies

Is there are different between List x; and List x(); in C++

ans-yes bcoz x(); isa function & list x; is a data type.

Please don't bring these old threads, that have been posted in the wrong spot, back to life.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.