Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to initialize member variables of Class in C++

Tags:

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:

test.cpp

#include<iostream>
using namespace std;

class Point {
private:
    int x;
    int y;
public:
    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 !

like image 609
mehtame026 Avatar asked Dec 01 '25 17:12

mehtame026


1 Answers

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.

like image 94
Brick Avatar answered Dec 04 '25 06:12

Brick



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!