conversions: objects to basic types/vice versa

This is a discussion on conversions: objects to basic types/vice versa within the C++ Programming forums, part of the General Programming Boards category; im following a book that has an example of converting objects to basic types and vice versa. ive checked the ...

  1. #1
    Registered User xion's Avatar
    Join Date
    Jul 2003
    Posts
    63

    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.
    Code:
    books output:
    1:  7 feet 8.51949 inches
    1:  2.35 meters
    2:  1.78435 meters
    
    my output:
    1:  7 feet 8.51949 inches
    1:  2.35 meters
    2:  -2.92738 meters
    --------------------------------------
    #include<iostream>
    using namespace std;
    ////////////////////////////////////
    class Distance		//english Distance class
    {
    
    private:
    	const float MTF;				//meters to feet
    	int feet;
    	float inches;
    
    public:
    	Distance() : feet(0), inches (0.0), MTF(3.280833F)
    	{	}
    	
    	Distance(float meters): MTF(3.280833F)		//convert meters to Distance
    	{
    		float fltfeet = MTF * meters;		//convert float to feet
    		feet = int(fltfeet);			//feet is the integer part so strip it
    		inches = 12 * (fltfeet - feet);		//inches is whats left
    	}
    
    	Distance(int ft,float in)	:	feet(ft),inches(in)
    	{	}
    
    	void getdist()	//get length from user
    	{
    		cout << "enter feet:  ";	cin >> feet;
    		cout << "enter inches:  ";	cin >> inches;
    	}
    
    	void showdist() const				//display distance
    	{	cout << feet << " feet " << inches << " inches" << endl; }
    	
    	operator float() const				//conversion operator
    	{						//converts Distance to meters
    		float fracfeet = inches / 12;		//convert the inches
    		fracfeet += static_cast<float>(feet); 	//add the feet
    		return fracfeet/MTF;
    	}
    	
    };
    //////////////////////////////////////
    
    int main()
    {
    	float mtrs;
    	Distance dist1 = 2.35F;				//one arg constructor convert meters to Distance
    	
    	cout << "1:  "; dist1.showdist();
    	
    	mtrs = static_cast<float>(dist1);		//USES CONVERSION operator for distance to meters
    	cout << "\n1:  " << mtrs << endl;
    	
    	Distance dist2(5, 10.25);
    	
    	mtrs = dist2;					//also uses conversion operator
    	cout << "\n2:  " << mtrs << endl;
    	
    //	dist2 = mtrs;			//WRONG:  '=' wont convert
    	return 0;
    }
    for the last value it always turns up negative for me. why is that?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >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:
    Code:
    Distance(int ft,float in):feet(ft),inches(in),MTF(3.280833F)
    {}
    My best code is written with the delete key.

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    The constant should be static too, it doesn't make much sense to have a copy of that for each instance.
    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

  4. #4
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359
    Hi am I seeing things? I have never seen class initalisation like that before.

    Code:
    Distance() : feet(0), inches (0.0), MTF(3.280833F)
    {}
    I usually do something like this:

    Code:
    Distance()
    {
      this.feet = 0;
      this.inches = 0;
      this.MTF = 3.280833F; //etc
    }
    Be a leader and not a follower.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Hi am I seeing things?
    Nope

    >I have never seen class initalisation like that before.
    It's an initialization list for a constructor. Perfectly legal and preferred over your method most of the time.

    >I usually do something like this
    That works too as long as none of the members are const.
    My best code is written with the delete key.

  6. #6
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359
    Hmmm, I like! :-) I shall be using that from now on. Usually if I declare any constants for a c/c++ class I usually declare them statically.
    Be a leader and not a follower.

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Which is usually better.
    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

  8. #8
    Registered User xion's Avatar
    Join Date
    Jul 2003
    Posts
    63
    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.)

  9. #9
    Registered User
    Join Date
    May 2004
    Posts
    4
    Quote Originally Posted by subdene
    Hi am I seeing things? I have never seen class initalisation like that before.

    Code:
    Distance() : feet(0), inches (0.0), MTF(3.280833F)
    {}
    I usually do something like this:

    Code:
    Distance()
    {
      this.feet = 0;
      this.inches = 0;
      this.MTF = 3.280833F; //etc
    }
    I would have to agree with subden's way of writing. Xions way of writing saves space but subden's is much easier to read. But it is just a style and neither way is wrong or right.

  10. #10
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    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

  11. #11
    Normal vector Carlos's Avatar
    Join Date
    Sep 2001
    Location
    Budapest
    Posts
    463
    this.feet = 0;
    this.inches = 0;
    this.MTF = 3.280833F; //etc
    Again, a good example on missusing the this pointer. I've seen it in some other threads too - I think once people get the taste of this, they use it without a reason...

    The same applies for inicialization lists. A bad example:
    Code:
    class Dummy
    {
    private:
    int i1, i2, i3, i4, i5, i6, i7;
    
    public:
    Dummy( int i1_in, int i2_in, int i2_in, int i4_in, int i5_in, int i6_in, int i7_in ) : i1(i1_in), i2(i2_in), i3(i3_in), i4(i4_in), i5(i5_in), i6(i6_in), i7(i7_in)
    //.
    
    };
    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!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [ANN] New script engine (Basic sintax)
    By MKTMK in forum C++ Programming
    Replies: 1
    Last Post: 11-01-2005, 09:28 AM
  2. what are your thoughts on visual basic?
    By orion- in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 09-22-2005, 04:28 AM
  3. array of objects?
    By *~*~*~* in forum C++ Programming
    Replies: 4
    Last Post: 05-31-2003, 05:57 PM
  4. Run Visual Basic (ActiveX objects) from inside C-code?
    By torbjoen in forum Windows Programming
    Replies: 0
    Last Post: 07-31-2002, 12:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21