When an object of type Counter is first created, we want its count to be initialized to 0. After all, most counts start at 0. We could provide a set_count() function to do this and call it with an argument of 0, or we could provide a zero_count() function, which would always set count to 0. However, such functions would need to be executed every time we created a Counter object.
Counter c1; //every time we do this,
c1.zero_count(); //we must do this too
This is mistake prone, because the programmer may forget to initialize the object after creating it. It’s more reliable and convenient, especially when there are a great many objects of a given class, to cause each object to initialize itself when it’s created. In the Counter class, the constructor Counter() does this. This function is called automatically whenever a new object of type Counter is created. Thus in main(), the statement
Counter c1, c2;
Sunday, October 26, 2008
Automatic Initialization
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment