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 ?
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
CodePudding user response:
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;
};