pokche pokche - 3 months ago 7
C++ Question

how can I value initialize private struct member of class via initialization list of constructor in c++?

Lets say I have a struct of POD type.

// A.hpp
//struct is of POD type
struct s {
int x;
double y;
};


Then I have this struct become private member of the class A

// A.hpp
class A{
s my_struct;
int size;
public:
A(int, double, int);

};


Now I want to initialize the class using constructor and I also want to initialize the my_sruct.

What I have so far is

// A.cpp
A::A(int x_, double y_, int size_):my_struct(x_, y_), size(size_){}

// main.cpp
A a( 4, 6.6, 7); // this is how I try to instantiate the object


But I get error saying


error: no matching function for call to 's::s(int&, double&)'


I could solve it by placing a constructor in the struct s. But I thought for POD we did not need to do that. Am I missing something here?

Answer

Change this:

A::A(int x_, double y_, int size_):my_struct(x_, y_), size(size_){}

to this:

A::A(int x_, double y_, int size_):my_struct({x_, y_}), size(size_){}

Minimal example:

struct s {
    int x;
    double y;
};

class A{
    s my_struct;
    int size;
public:
    A(int, double, int);

};

A::A(int x_, double y_, int size_):my_struct({x_, y_}), size(size_){}

int main() {
    A a( 4, 6.6, 7);
    return 0;
}

Compilation:

C02QT2UBFVH6-lm:~ gsamaras$ g++ -std=c++11 main.cpp
C02QT2UBFVH6-lm:~ gsamaras$

Otherwise, you may follow this answer.

Comments