Initialize members

Hi, I'm trying to learn C++ but am stuck on understanding the concept of initializing members. I don't know the reasoning behind this and how it works.
If a class has data members, then, when we create an instance of the class, it may be necessary to initialize those members with data values.

This can be done in a constructor of the class.
Last edited on
To "initialise" a variable means "to give it an initial value at the same time as you create it".

Thus, to initialise a member means to give it a value at the same time as you create the object that contains it.

Typically, this is done in the constructor of the object.

Can you be more specific about what it is you don't understand?
Think about the opposite case: uninitialized objects.


Q: How many times will this loop repeat?
1
2
3
4
5
int x; // uninitialized
while ( 7 < x ) {
  // fubar
  --x;
}

A: Nobody knows. The value of x is undefined.

Q: Ahh, but int is not class. Surely a class:
1
2
3
4
5
struct Point {
  int x; int y;
};

Point bar; // Where is it? 

A: Should it really do more work by default than the int does?

Q: One more time:
1
2
3
4
5
class Circle {
  Point pos;
  float r;
  float area; // cached value, must always == r*r*pi()
};

The area is computed from r. One could always recompute it, but this time memory is cheaper. However, the area must be updated whenever the r changes, including on creation of a circle.

In other words, all objects (including ints and chars) should always (or at least before they are used) have a known and consistent state. How would you feel about receiving a wallet full of $1000 bills that tells that it has only 42 cents in it? Inconsistent, incoherent.
so it should look something like this?

1
2
3
4
Date::Date(int yy,int mm, int dd)
	: y{yy}, m{mm}, d{dd}
{
}
Yes, that is initialization.
Thank you
Topic archived. No new replies allowed.