ecmadeeasy
ecmadeeasy

Reputation: 17

To use a non-initial value for a variable

Consider the following example of a code:

class MyClass {
    public:
    MyClass( float f, char a );

    private:
    int b;
};

By declaring like this, is the initial value of integer b is set to zero by deafult?

If this is possible, can I change the value of b like: (bear in mind that the following code will be called a number of times and the value assigned to b each time is required for the next iteration of the procedure)

int fg = int(ds/r);
int temp1;
if(b==0) {
    temp1=0;
}

temp1=b;
b=fg;

Upvotes: 0

Views: 75

Answers (4)

juanchopanza
juanchopanza

Reputation: 227608

By declaring like this, is the initial value of integer b is set to zero by deafult?

It all depends on the implementation of your constructor. If you don't do anything about it, then the value of b is unspecified.

To ensure it is set to 0, you would need something like this in your constructor(s) implementation(s):

 MyClass::MyClass( float f, char a ) : b() {}

Note that in C++11 you can initialize a data member at the point of declaration, so you can do this:

class MyClass {
  public:
    MyClass( float f, char a );

  private:
    int b = 0; // or int b{0}, but not int b(0)
};

Upvotes: 2

Andrew
Andrew

Reputation: 24866

By default it is not initialized.

In C++ 11 you can just write:

private:
    int b = 0;

Now any constructor of the class will initialize value of b with 0 if you don't explicity say otherwise

Upvotes: 3

W.B.
W.B.

Reputation: 5525

Th variable is uninitialised, which means that its value is undefined (random trash).

You can set the values like you want. There's no problem with that (as long as b has been initialised).

Upvotes: 0

billz
billz

Reputation: 45470

variable b is not initialized to 0 if you don't initialize it in constructor(suggest initialize it in member initializers list)

MyClass( float f, char a ) : b(0) { }

Upvotes: 1

Related Questions