conversions: objects to basic types/vice versa

im following a book that has an example of converting objects to basic types and vice versa. ive checked the code numerous times but i get a different output than what the book is saying. in this case im trying to convert Distance (feet and inches) into meters and vice versa.

>const float MTF;
This must be initialized in the constructor initialization list.

>Distance(int ft,float in):feet(ft),inches(in)
Notice how you neglect to do so here.

>Distance dist2(5, 10.25);
And you call that constructor here.

For some reason, your compiler is allowing you to leave a const member uninitialized. This should be an error as it's a constraint violation, but using the uninitialized value is giving you incorrect results due to undefined behavior. Replacing your last constructor with this one fixes the problem and gives the correct output:

thanks prelude, overlooked that MTF var. for some reason it thought that variable was declared and defined at the same time.

p.s. i been switching back and forth through c++ and c. k&r is giving me trouble so i guess ill stick to robert lafore's text on c++ for a while until i get more comfortable with programming. heh (not that anyone cared.)

Actually in some cases the second IS wrong. This one, for example, will not compile because MTF must be initialized, not assigned. Constructor calls to base classes and contained classes must be written in the first way, especially if there is no default constructor. Generally the first way is better for the compiler.

All the buzzt! CornedBee

"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law

Just one more thought on inicialization lists:
- for built-in types it should be used only to initialize constants and references (there's no other way unless declared as static)
- the real benefit of initialization lists is initialization of user defined data members (classes and structs), as instead of construction and a call to "operator =" only the copy constructor is called

One more thing: the order in the inicialization lists should respect the declaration order, else interesting things might occur!