Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 914
user2991252 Avatar asked Jan 24 '26 02:01

user2991252


2 Answers

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.

like image 52
Sergey Kalinichenko Avatar answered Jan 25 '26 15:01

Sergey Kalinichenko


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]) {
 }
like image 21
πάντα ῥεῖ Avatar answered Jan 25 '26 15:01

πάντα ῥεῖ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!