Pallav Doshi
Pallav Doshi

Reputation: 199

Are all the data members initialized to 0 or are they assigned random values by the constructor which is called automatically?

I tried to check what values are assigned to the data members when we do not call a constructor manually. I got 0 for both a and b, but I got 1 for c, so how are the data members initialized? Randomly or to 0? And if they are initialized to 0, why am I seeing 1 as the value for c?

#include<iostream>
using namespace std;

class Class
{
    public:
        int a,b,c;      
};

int main()
{
    Class obj;

    cout<<obj.a;
    cout<<"\n";
    cout<<obj.b;
    cout<<"\n";
    cout<<obj.c;

    return 0;
}

The output is 0 0 1

But I expected 0 0 0

Upvotes: 3

Views: 57

Answers (1)

atru
atru

Reputation: 4744

As stated here the default initialization in your case will led to "undetermined" i.e. undefined values.

The compiler will provide you with a default constructor because you haven't defined it yourself and did not defined any other constructors (it will delete it in that case), but the default constructor will still make the member values undefined. You were getting 0s and a 1 - I was getting numbers more like 1515788312.

With C++11 standard you can prevent this by providing the default values directly in the class,

#include<iostream>
using namespace std;

class Class
{
public:
    int a = 0, b = 0, c = 0;
};

int main()
{
    Class obj;

    cout<< obj.a << " "
        << obj.b << " " << obj.c << endl;

    return 0;
}

In this case, the values will be initialized to whatever you set them to be. To achieve the same thing you can also simply provide your own default constructor,

#include<iostream>
using namespace std;

class Class
{
public:
    Class() : a(1), b(2), c(3) { }
    int a, b, c;
};

int main()
{
    Class obj;

    cout<< obj.a << " "
        << obj.b << " " << obj.c << endl;

    return 0;
}

As a side note, avoid using namespace std due to possible name collisions. Use individual using statements instead - for things you commonly use like cout. I changed your program a little bit for clarity. Also, the answers to your question can be found well explained in various C++ books, like Lippman's Primer which I used.

Upvotes: 1

Related Questions