Can I declare object literals using names rather than of types?

  • A+
Category:Languages

In JavaScript I would declare an object as:

rectangle = {     length: 4,     height: 2 } 

In C++ I do it like this

struct Rectangle {     int length;     int height; };  rectangle = Rectangle {     int {4},     int {2} } 

The C++ style I not as good as the JavaScript style in my opinion, because:

  • Types convey less relevant information than names
  • properties can not be listed in arbitrary order

Is it possible to declare C++ objects in a way that is more similar to the JavaScript way?

 


Since C++20 you can do:

auto rectangle = Rectangle{ .length = 4, .height = 2 }; 

Some compilers have started to support this syntax already, even though C++20 is not released yet.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: