Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Class members with zero

Tags:

c++

I have a class in my code that has some integer data members but no methods. Is there exist a way to initialize all the data items with 0 when I create a new object of it using new()?

like image 343
NeonGlow Avatar asked Dec 04 '25 17:12

NeonGlow


1 Answers

class A
{
    int x_; 
    int y_; 

    public: 
        A() 
           : 
             x_(0),
             y_(0)
        {} 
};

The part of the A() constructor before the brackets "{}" is called an "initializer list", which you use to initialize the variables to a default value 0 in the case above, or to some other values that may be passed to a constructor that might take those values as arguments. However you initialize an object of type A (e.g. with "new"), the attributes will be initialized to those values. It is good coding style to initialize the attributes in the same order they are declared, it makes the code more readable.

like image 188
tmaric Avatar answered Dec 06 '25 06:12

tmaric



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!