0

I’ve come across an error initializing a class that I have in a separate header. The issue came up once I added inputs to the class constructor being defined in my header. In a file called my_header.h I have,

class A {
private:
    int a;
public:
    A (int a_in = 1) : a(a_in) {}
};

I then want to use this class in another file, my_class.cpp. my_class also has a header, which is where I define my variables, so in my_class.hpp I have

#include "my_header.h"

class B {
private:
    A a1; // no problems
    A a2(2); // errors: "Expected ')'" and "Expected parameter declarator"
    int a_in = 3;
    A a3(a_in); // error: "Unknown type name 'a_in'"
public:
    A return_A ();
};

Ideally, I would like to use a_in as a variable later on for user input, which is why I want to use it for initialization.

I realize, based on the error, that the compiler cannot pickup what the parameter going into A::A(int a_in) is. I know that this can be solved by calling A::A(int a_in) in the constructor of B, thanks to this post.

However, is there another way to explicitly call A::A(int a_in) without having to do it in the definition of the B constructor? I would prefer to keep my B constructor definition in the .cpp file and initialize the variables, with inputs, in the .hpp file.

Edit: Solution

Use curly brackets

int a_in = 3;
A a3 {a_in};
MoogsDoog
  • 53
  • 4
  • `A a3 {a_in};`, see 2) here: https://en.cppreference.com/w/cpp/language/data_members#Member_initialization (`A a3 = a_in;` should do the trick too) `()` brackets are interpreted as start/end of the parameter list of a member function declaration, if you place code like `A a3(a_in);` in this kind of context. – fabian Dec 01 '21 at 19:34
  • Thanks fabian that works! I'm not used to using curly brackets for initialization, but I'm sure I will be doing more of that after having looked into it more. Bjarne seems to recommend it, https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives – MoogsDoog Dec 02 '21 at 17:00

0 Answers0