user2991252
user2991252

Reputation: 788

Initialize member-variables in header-file

I get compilation warnings when I initialize the following member variables in the header-file

private:
  const std::string FILENAME = "prices.txt";
  double *temp = new double[SIZE];

Warning: non static data member initializers only available with -std=c++11 or std=gnu++11

How do I best fix this? Should i just declare the variables in the header-file and then initialize them in the constructor?

Upvotes: 2

Views: 8062

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

The compiler suggests one solution: add -std=c++11 flag to the compiler to enable this C++11 feature. This would add a lot of other features that make C++ programming a lot more enjoyable.

If switching to C++11 is not an option for you, use initializer list in the constructor:

MyClass() : FILENAME("prices.txt"), temp(new double[SIZE]) {}

Note: Since you create a temp in the dynamic memory area, you need to add a destructor, a copy constructor, and an assignment operator. You would be better off using a dynamic container, e.g. std::vector for your data, because it simplifies your memory management code.

Upvotes: 9

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

How do I best fix this? Should i just declare the variables in the header-file and then initialize them in the constructor?

Yes! Since the const std::string you'll need a member initializer list:

 MyClass::MyClass() 
 : FILENAME("prices.txt")
 , temp(new double[SIZE]) {
 }

Upvotes: 1

Related Questions