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};