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.
What is wrong with it? Or I do not see something obvios?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With