Thread: help with class and constructors

  1. #1
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195

    help with class and constructors

    i am a real new with c++, so bare with me here. i have this assignment that asks for a rational number class that overloads the +,-,/,*. I pretty much know how i am going to do it, but there is some specs i don't understand.

    the problem says to use a constructor to make sure the denoninator is never zero. now i thought that a constructor was only called as the object was being created, not as it everytime it is used. i am not sure how do do this. i have only used constructors for initializations before now....

    for example...

    Code:
    class RationalNumber {
      public:
          RationalNumber(int 0, int 1); // this would justt be a default initialization to 0/1
           RationalNumber();  // this one would need to be called every time i need to check to see if the denominator is zero?????
     };
    
        RatoinalNumber::RationalNumber( int num, int den) 
    {
        num = 0;
        den = 1;
    }
    
    RationalNUmber::RationalNumber()
    {
      //do some checking
      //do what ever needs to be done
    }
    i don't really get it. am i misuderstanding the constructor?
    'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition

  2. #2
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    You seem to be on the right track here. And you seem to understand what you are doing. You don't need the void constructor. But your syntax is a little off for the default numbers for your parameters in your fist constructor. You should be using =1 not just 1. Unless of course your compiler is a genious and knows that you aren't trying to use 1 as the name of a parameter, in which case go ahead

  3. #3
    julie lexx... btq's Avatar
    Join Date
    Jun 2002
    Posts
    161
    as far as I know the constructor only gets called on initilization,
    so if you were to check something with it, it's when you create
    the instance. So maybe somethin like:

    Code:
    class RationalNumber {
      public:
      int denom,numer;  
        RationalNumber(int num, int den); // this would justt be a default initialization to 0/1
           RationalNumber();  // this one would need to be called every time i need to check to see if the denominator is zero?????
     };
    
        RatoinalNumber::RationalNumber( int num, int den) 
    {
        numer=num;
        if(!den)  //checking if den==0, if so set it to 1..
            denom = 1;
        else
             denom=den;    
    
    }
    
    RationalNUmber::RationalNumber()
    {
      //do some checking
      //do what ever needs to be done
    }
    now if you call it like: RationalNumber myNum(2,0)
    you'll have a number 2/1...

    /btq

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    You can set the den to 1 if they try use zero, but persoanlly i would prefer to throw an exception.....maybe a bit harsh, but I dont like classes and functions that change params without notification

    Also, you can use a constructor with default values...this can act as a normal default constructor, and you can add param checking in the body of the function (in this case I throw an exception)

    Code:
    #include <iostream>
    
    class RationalNumber {
    	
    public:
    	int num,den;//these would normally be private!
        RationalNumber(int n = 0, int d = 1):num(n),den(d)
        	{if(!den)throw DenIsSetAsZeroException();}
        class DenIsSetAsZeroException{};//exception for use with class
        //...extra stuff...assignments operators, copy constructors....
    };
    
    
    
    int main(){	
    
    	try{
    		RationalNumber a;//acts like default constructor (1,0)
    		std::cout << "num & den = " << a.num << " " << a.den << std::endl;
    	}
    	catch(RationalNumber::DenIsSetAsZeroException&){
    		std::cout << "Error caught! den is zero!" << std::endl;
    	}
    	
    	try{
    		RationalNumber b(10,20);//fine
    		std::cout << "num & den = " << b.num << " " << b.den << std::endl;
    	}
    	catch(RationalNumber::DenIsSetAsZeroException&){
    		std::cout << "Error caught! den is zero!" << std::endl;
    	}
    	
    	try{
    		RationalNumber c(1,0);//oh dear!!!
    		std::cout << "num & den = " << c.num << " " << c.den << std::endl;
    	}
    	catch(RationalNumber::DenIsSetAsZeroException&){
    		std::cout << "Error caught! den is zero!" << std::endl;
    	}
    
    }

  5. #5
    Just a Member ammar's Avatar
    Join Date
    Jun 2002
    Posts
    953
    I think everything is OK but for this:
    RationalNumber(int 0, int 1);
    I think the syntax is wrong., it should be:
    RationalNumber(int num, int den);
    then is the definition you do the default arguments.

    I don't get why Fordy used the member initializer?

    when you wrote: RationalNUmber::RationalNumber()
    you overloaded the constructor which is not what I think you need, then checking should be in the pervious function where you receive arguments because it you don't receice arguments how can you check them

  6. #6
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Originally posted by ammar
    I don't get why Fordy used the member initializer?
    Why not?

    If I pass no params, the default values {0,1} kick in, but if I pass an explicit value to the constructor, those defaults are not used, and the members are intialised to the proper values

  7. #7
    Just a Member ammar's Avatar
    Join Date
    Jun 2002
    Posts
    953
    RationalNumber(int n = 0, int d = 1):num(n),den(d)
    I mean why didn't we use the normal assignment operator : num=n and den=d,num and den are not const.
    I'm new to C++ so can you tell me if it's better to use the member initializer syntax, maybe it's better because if the member was const we don't have to re write the ctor.

  8. #8
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195
    fordy, thanks i like how you did that, and i want to use it. But i don't understand everthing you did.

    In particular the line under public:
    class DenIsSetAsZeroException{};//exception for use with class

    i don't really get how that works...
    'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition

  9. #9
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Originally posted by stautze
    fordy, thanks i like how you did that, and i want to use it. But i don't understand everthing you did.

    In particular the line under public:
    class DenIsSetAsZeroException{};//exception for use with class

    i don't really get how that works...
    Your createing another class within a class...so when I encounter an error, my class throws an exception based on the inner class (that inner class may have members to say what's wrong etc....)...

    Then in my main code I just watch out for an exception of type RationalNumber:enIsSetAsZeroException (Outerclass::Innerclass)....

  10. #10
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195
    correct me if i am wrong, but the way you have it written the class DenominatorIsSetAsZeroException needs no members?

    Would it look like this though if I added members:
    Code:
    class DenominatorIsSetAsZeroException{
      public:
        DenominatorIsSetAsZeroException()
           :message("attempted to set denominator to zero") {}
        const char *what() const {return message;}
      private:
         const char *message;
    };
    And this could be just placed inside the other class definition? Sort of like embedding a class in another class?
    Sorry i am new to C++....
    'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition

  11. #11
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    You can add members if you wish...Many people dont, but the option is there....I think this should work;

    Code:
    #include <iostream>
    #include <string>
    
    
    class RationalNumber {
    
    public:
    	int num,den;//these would normally be private!
    	
    	RationalNumber(int n = 0, int d = 1):num(n),den(d)
    		{if(!den)throw DenIsSetAsZeroException("Divide by Zero Exception");}
        
    	class DenIsSetAsZeroException{
    	public:
    		std::string m_str;
    		DenIsSetAsZeroException(const char* str):m_str(str){};
    	};
    
        
    };
    
    
    
    int main(){
    
    	//..............
    
    	try{
    		RationalNumber c(1,0);//oh dear!!!
    			std::cout << "num & den = " << c.num << " " << c.den << std::endl;
    	}
    	catch(RationalNumber::DenIsSetAsZeroException& e){
    		std::cout << e.m_str << std::endl;
    	}
    
    }
    Of course your version will likely be more robust than mine (access restictions...) but that's a basic idea

  12. #12
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195
    >Of course your version will likely be more robust than mine (access restictions...) but that's a basic idea

    probably not , whats an access restriction?
    'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition

  13. #13
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    "I am new to c++", and you're telling him to throw and catch exceptions already? And throwing classes at that?? Yeesh, might as well tell him to learn Winsock API! (I heard that's difficult to figure out )

    P.S.

    I think that what he means by "access restrictions" means something like making some of the variables private/protected... don't quote me or anything, tho
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  14. #14
    Registered User stautze's Avatar
    Join Date
    Apr 2002
    Posts
    195
    > "I am new to c++", and you're telling him to throw and catch exceptions already? And throwing classes at that?? Yeesh, might as well tell him to learn Winsock API! (I heard that's difficult to figure out )


    I might be a bit misleading, because i have been programming in C for a few years....
    'During my service in the United States Congress, I took the initiative in creating the Internet.' - Al Gore, March 9, 1999: On CNN's Late Edition

  15. #15
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Alrighty then, so you're not an easily confused one.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A question about class members and constructors
    By Megidolaon in forum C++ Programming
    Replies: 5
    Last Post: 01-30-2009, 03:01 PM
  2. Replies: 4
    Last Post: 12-29-2002, 12:29 AM
  3. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM
  4. Constructors + Derived class
    By MethodMan in forum C++ Programming
    Replies: 6
    Last Post: 11-10-2002, 05:05 PM
  5. Constructors of a class
    By casanova0o7 in forum C++ Programming
    Replies: 3
    Last Post: 01-31-2002, 03:46 PM