Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class data default initialization

I have following code:

#include <iostream>
using namespace std;

class Base
{
private:
    int i;
    char ch;
public:
    void showdata()
    {
        cout<<"Int:"<<i<<endl;
        cout<<"Char:"<<ch<<endl;
    }
    //int pub_data ;
} ;

int main()
{
    Base ob;
    ob.showdata() ;
    //cout<<"Public Data:"<<ob.pub_data<<endl;
    return 0;
}

This program compiles and runs fine. The output shows that i is initialized with 0 and ch is initialized with '\0'.
If you notice i have commented out 2 statements in this program. First the declaration of public data pub_data and second the line inside main printing this public data.
Now here the problem is, if i uncomment these two lines, the data members of class i.e. i, ch, pub_data do not seem to be initialized and when printed, they display junk values.
So my question is what difference public data makes here?
I'm using g++ 3.4.6

like image 849
mukeshkumar Avatar asked Jan 30 '10 06:01

mukeshkumar


People also ask

Are class members default initialized C++?

C++ initializes class members in the order they are declared, not the order they appear in the initializer list.

What is default initialization in Java?

For type int, the default value is zero, that is, 0. For type long, the default value is zero, that is, 0L. For type float, the default value is positive zero, that is, 0.0f. For type double, the default value is positive zero, that is, 0.0d. For type char, the default value is the null character, that is, '\u0000'.

What is initialization of class?

A class initialization block is a block of statements preceded by the static keyword that's introduced into the class's body. When the class loads, these statements are executed.

What is default initialized C++?

Default member initializer (C++11) [edit] This is the initialization performed when an object is constructed with no initializer.


2 Answers

Neither int's nor char's are automatically initialized to 0. The fact that it happened is just luck.

You need to add a constructor that does the initialization:

Base() : i(0), ch(0) {}
like image 142
R Samuel Klatchko Avatar answered Sep 30 '22 14:09

R Samuel Klatchko


None. You're just getting "lucky". Fundamental types remain uninitialized, so your i and ch, as the program stands, could very well not always be 0.

It just so happens adding that public member "messes it up". To correct your class, initialize the members in the initialization list of the constructor:

class Base
{
private:
    int i;
    char ch;
public:
    Base(void) :
    i(0), ch(0) //, pub_data(0)
    {}

    void showdata()
    {
        cout<<"Int:"<<i<<endl;
        cout<<"Char:"<<ch<<endl;
    }
    //int pub_data ;
} ;

Now when a Base gets constructed i, ch, and (when uncommented) pub_data will be properly initialized to meaningful values.

like image 41
GManNickG Avatar answered Sep 30 '22 15:09

GManNickG