0

I remember in college there was a way to make initialize an object writing a series of member variables initialization, separated by commas like in the code example from bellow, but i cant remember how it was called.

class A
{
public:
    string s1, s2, s3;
    A()
    {

    }
};
#include "A.h"

int main()
{
    A a
    {
        s1 = "String1",
        s2 = "String 2",
        s3 ="String 3"
    }
}

What else should i type in order for that constructor like list to work?

  • 1
    [Member initializer list](https://en.cppreference.com/w/cpp/language/initializer_list). – Quentin Oct 30 '19 at 16:30
  • 1
    See: https://en.cppreference.com/w/cpp/language/aggregate_initialization#Designated_initializers – NathanOliver Oct 30 '19 at 16:31
  • 1
    Short answer is no – Moia Oct 30 '19 at 17:21
  • I hesitate to call it a [duplicate](https://stackoverflow.com/q/18731707/10957435), but good reading on the subject. The sort answer is what you are asking to do is not allowed in C++. –  Oct 30 '19 at 18:17
  • I stand corrected. It may be possible [in c++20](https://stackoverflow.com/a/29337570/10957435) and with boost. –  Oct 30 '19 at 18:19

2 Answers2

1

Your code, with proper constructor:

class A
{
    public:
    string s1, s2, s3;
    A(string a, string b, string c): s1{a},s2{b},s3{c}
    {

    }
};

Now you can initialize objects of this class as:

A a("String1","String2","String3");

If you are interested you can refer from here: https://en.cppreference.com/w/cpp/language/initializer_list

If you want named arguments, well C++ doesn't have named arguments, here is a proposal that might get implemented in future (It's not in C++17): http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4172.htm

If you still want named arguments, here is a FluentCpp article on how to get it working: https://www.fluentcpp.com/2018/12/14/named-arguments-cpp/

MrProgrammer
  • 443
  • 3
  • 13
  • 1
    I should say that is a very encrypted way to attributes value for object – olegario Oct 30 '19 at 17:10
  • But i dont want that. Please read my code again. I want to specify which variable to take which value, independent of the order i put them, like this : {s1="String1", s2="String2"} – Robert Puscasu Oct 30 '19 at 17:15
1

Not in C++, but C99 does support this (designated initializers).

struct point { int x, y; };

struct point p = { .y = yvalue, .x = xvalue };

https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

Jim Lahey
  • 84
  • 1
  • 2