Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ default constructor fails to initialize public variables?

I have simple sample:

#include <iostream>

class parent {
public:
    int i;
};

class child : public parent {
public:
    int d;
};

int main() {
    child c;
    std::cout << c.d << std::endl;
    return 0;
}

If you do not explicitly initialize a base class or member that has constructors by calling a constructor, the compiler automatically initializes the base class or member with a default constructor.

but all ints in c (int d; and int i;) are not initialized.

enter image description here

What is wrong with it? Or I do not see something obvios?

like image 697
myWallJSON Avatar asked Dec 20 '22 10:12

myWallJSON


2 Answers

With built-in types, you actually have to do the initialization yourself:

class parent
{
 public:
  parent() : i() {}
  int i;
};

This will initialize i to 0.

like image 132
juanchopanza Avatar answered Dec 23 '22 00:12

juanchopanza


Built in data types (like int) are not really initialized. Their "default constructor" does nothing and they have no default value. Hence, they just get junk values. You have to explicitly initialize built in data types if you want them to have a specific value.

like image 39
Cornstalks Avatar answered Dec 23 '22 00:12

Cornstalks