ronme026 ronme026 - 1 year ago 82
C++ Question

Where to initialize member variables of Class in C++

I just started using C++. I have a question. Where should I initialize class member variables? I have assigned some value to members variables using some member function. But static analysis tool is complaining about member initialization in constructor. See following example:


using namespace std;

class Point {
int x;
int y;
Point(int r)
y = r;

inline void setXval(int x_val) {
x = x_val;

Here, that tool says that x is not initialized in constructor. But I am setting x value in member function. Is it correct way to do this or we should always initialize all members in default constructor? Any help is much appreciated. Thanks in advance !

Answer Source

All variables should get an explicit value in the constructor. You're not giving any value to x, so your tool is correct. You might or might not call the member function that sets the value for x later - You cannot count that you (or a user of your code) will call that function before you need the value of x somewhere.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download