Hi,
A a1 = A(); // Default const
cout << a1.i; // Print garbage..don't expect 0
The above is true. But if we replace A with a built-in type, say int, its
value will be initialized by 1st line. I'm worried, because this makes
user-defined types inferior in some way to built-in types. At least it makes
them behave differently, as there's no way to distinguish between these 2
construction types (available with built-in types):
1. Construct and leave members uninitialized
2. Construct and initialize members to default values, specific for each
member
Or at least there's no elegant way (by elegant I mean the way built-in types
are initialized).
Marcin
U¿ytkownik "Sharad Kala" <
[email protected]> napisa³ w
wiadomoœci
Marcin Kalicinski said:
Hi all,
Thanks for your answer, but if it is true, how do I define my custom class
so that it follows the same schema? It seems impossible, because there's no
way to distinguish between these 2 types of initialization when writing
class definition. Both are handled by default constructor.
To be specific, I'd like to define class Vector3, which is a 3 dimensional
vector. If I initialize coordinates to zeroes in default constructor, I get
behavior 'i2'. If I do not initialize, I get behavior 'i1'. But I'd like to
get both if them, so that Vector3 does not differ in this important point
from built-in types. Additionally, Vector3 is to be used in
performance-critical code, so I'd like to avoid unnecesary initialization if
possible - so 'i1' behavior is probably a must to have.
You got it wrong.
The default constructor for int, float, bool initializes them to 0 /false.
But that does not mean that ints, floats etc in UDTs will also be default
initialized in the default constructor.
In this code -
#include <iostream>
using namespace std;
struct A{
int i;
A(){}
A(int I):i(I){}
};
int main(){
A a1 = A(); // Default const
cout << a1.i; // Print garbage..don't expect 0
A a2(10);
cout << a2.i; // Print 10
}