Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why by default without constructor the variable or pointer values of the user defined class in cpp points to 0 or NULL?

I have a very simple class node where I have two variables and one pointer int, string and pointer to same class when I am printing them without any initialization

The int shows zero, string empty string, and pointer point to NULL

My question is this, this is how it should be shouldn’t they be pointing to some random value and is this compiler specific thing ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Below is the code for the same

#include<iostream>
using namespace std;
class node{
public:
    int x;
    string y;
    node* ptr;
};
int main()
{
    node* node1=new node;
    cout<<node1->x<<endl;
    cout<<node1->y<<endl;
    cout<<node1->ptr;
    return 0;
}

Output the code gives in my compiler

0

0x0

Thanks a lot

>Solution :

shouldn’t they be pointing to some random value and is this compiler specific thing ?

No. The value is uninitialized and therefore the contents of the memory is undefined. Whether it is consistently zero or some other value in your local tests is completely irrelevant.

If you want to value-initialize the new memory without a constructor, then add parentheses in the call to new as follows:

node* node1 = new node();

The above guarantees that each member of node will be value-initialized. For the std::string member, that will be the default constructor (which it always was anyway). But for the members x and ptr this now guarantees they are zero.

Alternatively, you can provide a default constructor to initialize your values:

class node{
public:
    int x;
    string y;
    node* ptr;

    node()
        : x()
        , ptr()
    { }
};

Or you can use member-initialization syntax (unsure of the exact term) as of C++11:

class node{
public:
    int x = 0;
    string y;
    node* ptr = nullptr;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading