Thread: help with classes

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    494

    help with classes

    can someone give me an example of how to use classes? i read the tuorial and still dont get it, just a simple example of how to use functions in a class. this is what i got so far but im getting 3 errors on this.

    Code:
    #include	<iostream>   
    
    using namespace std;
    
    class Average
    
    {
    	public:
    		float findaverage();
    	
    	private:
    			int		score;
    			float	sum;
    			int     NumScores;
    };
    
    
    float Average::findaverage()
    
    {
    	float findaverage(int score, int NumScores);
    
    	cout <<"enter a score" << endl;
    
    	while ( score != 0 )
    	{
    		sum += score;
    		NumScores++; 
            cout << "Enter a test score ( 0 to quit ): "; 
            cin >> score; 
    	}
    
    
    	return sum/NumScores;
    
    }
    
    int main()
    {
    	Average Numbers;
    	Average.findaverage();
    
    	cout <<"The average is" << Average <<endl;
    	return 0;
    }
    When no one helps you out. Call google();

  2. #2
    Slave MadCow257's Avatar
    Join Date
    Jan 2005
    Posts
    735
    what are your errors?

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    Code:
    addit.cpp
    C:\Program Files\Microsoft Visual Studio\MyProjects\addit\addit.cpp(44) : error C2143: syntax error : missing ';' before '.'
    C:\Program Files\Microsoft Visual Studio\MyProjects\addit\addit.cpp(44) : error C2143: syntax error : missing ';' before '.'
    C:\Program Files\Microsoft Visual Studio\MyProjects\addit\addit.cpp(46) : error C2275: 'Average' : illegal use of this type as an expression
            C:\Program Files\Microsoft Visual Studio\MyProjects\addit\addit.cpp(10) : see declaration of 'Average'
    Error executing cl.exe.
    
    addit.obj - 3 error(s), 0 warning(s)
    When no one helps you out. Call google();

  4. #4
    People Love Me
    Join Date
    Jan 2003
    Posts
    412
    Code:
    #include <iostream>
    using namespace std;
    
    class Sprite{
     private:
       int HP;
       int MP;
       int Att;
       int Def;
       int Lvl;
    
     public:
       Sprite(int hp, int mp, int att, int def);
       ~Sprite();
       int getHP(){return HP;}
       int getMP(){return MP;}
       int getAtt(){return Att;}
       int getDef(){return Def;}
       int getLvl(){return Lvl;}
       void LvlUP();
    };
    
    Sprite::Sprite(int hp, int mp, int att, int def){
       Lvl=1; HP=hp; MP=mp; Att=att; Def=def;
    }
    
    void Sprite::LvlUP(){
       Lvl++;
       HP += Lvl*5;
       MP += Lvl;
       Att += Lvl;
       Def += Lvl;
    }
    
    int main(){
    /*A pointer that points to the whole class, and can de-reference anything inside of it*/
       Sprite *Sebba = new Sprite(50,10,5,5);
       cout << "Sebba has "<<Sebba->getHP()<<" hit points." <<endl;
       Sebba->LvlUP();
       cout << "Sebba now has "<<Sebba->getHP()<<" hit points." <<endl;
       return 0;
    }
    Last edited by Krak; 02-12-2005 at 10:56 AM.

  5. #5
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    thanks Krak ill check your example.
    When no one helps you out. Call google();

  6. #6
    People Love Me
    Join Date
    Jan 2003
    Posts
    412
    Quote Originally Posted by InvariantLoop
    thanks Krak ill check your example.
    I just updated it real quick so be sure you're reading the updated version that works okay.

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Code:
    #include    <iostream>   
    
    using namespace std;
    
    class Average
    
    {
        public:
            float findaverage();
                
        private:
                int score;
                float sum;
                int NumScores;
    };
    
    
    float Average::findaverage()
    {
        //float findaverage(int score, int NumScores);
        //The function header is included at the beginning of the definition, not inside the definition.
        //You already have the function header in the previous line.  In addition, you declared the function
        //without any parameters, so your function defintion cannot suddenly have two parameters:
    
    
        cout <<"enter a score" << endl;
    
        while ( score != 0 )
        {
            sum += score;
            NumScores++; 
            cout << "Enter a test score ( 0 to quit ): "; 
            cin >> score; 
        }
    
    
        return sum/NumScores;
    
    }
    
    int main()
    {
        Average Numbers;
        //Average.findaverage();
        //You declared a variable named Numbers of type Average, so Numbers is your variable name.  
        //It's similar to when you declare a variable like this: int num;
        //You wouldn't then do this: int = 10;
    
        //You can declare a variable to store the average.  The type of the variable has to be the
        //same type as the return type of the function.
        float avg = Numbers.findaverage();
        
        //cout <<"The average is" << Average <<endl;
        cout <<"The average is" << avg <<endl;
        return 0;
    }
    Now, you won't get any errors, however the result won't be correct. If you don't initialize your class member variables, they will contain junk values. So, when you do:

    sum += score;

    that's the same as:

    sum = sum + score;

    and sum on the right side of the equals sign does not equal zero the first time you do that--it contains some junk value. You have the same problem with:

    NumScores++;

    NumScores contains a junk value that you increment.

    The way you initialize class members is with a constructor function. A constructor function has the same name as the class, and it has no return type:
    Code:
    Average()
    {
        score = 0;
        sum = 0;
        NumScores = 0;
    
        cout<<"constructor was called"<<endl;
    }
    You don't have to pass member variables to a class function. Unlike regular variables, member variables are accessible directly from inside a class function. Notice in the constructor above, I did not pass score, sum, or NumScores to the function, yet I can still change their values inside the function. That is true with all class functions--you can use the member variables inside the function to change their values. The constructor will be called automatically whenever you create a class object, e.g Average Numbers.

    You will have to change your while loop condition because score will start off equaling 0.
    Last edited by 7stud; 02-12-2005 at 02:37 PM.

  8. #8
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    can you please explain more in detail? i see that it gives the wrong result but i dont undersatnd why? when i initialize sum =0; should i do this as private in the class?
    When no one helps you out. Call google();

  9. #9
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    when i initialize sum =0; should i do this as private in the class?
    You can't do this:

    private:
    int sum = 0;
    float sum = 0;
    int NumScores = 0;

    There are a couple of ways to assign values to members:
    1) make them public and then just assign 0 to them anywhere in your code in main().
    2) create a 'setter' function, which is a function that takes a parameter, and then sets the value of a private member to the value sent to the function
    3) use a constructor

    You should stick with 3).

    i see that it gives the wrong result but i dont undersatnd why?
    while ( score != 0 )

    score starts off equaling zero, so the loop is skipped. You could ask the user to enter -100 if they want to quit the loop and check for that instead.
    Last edited by 7stud; 02-12-2005 at 01:25 PM.

  10. #10
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    ok i used the initialization constructor but i still get the wrong result. 12/3 = 4 not 3.

    Code:
    #include    <iostream>   
    
    using namespace std;
    
    class Average
    
    {
        public:
                float findaverage();
                Average();
                
        private:
                int score;
                float sum;
                int NumScores;
    };
    Average::Average()
    {
        score = 0;
        sum = 0.0;
        NumScores = 0;
    
        cout<<"constructor was called"<<endl;
    }
    
    
    float Average::findaverage()
    {
        //float findaverage(int score, int NumScores);
        //The function header is included at the beginning of the definition, not inside the definition.
        //You already have the function header in the previous line.  In addition, you declared the function
        //without any parameters, so your function defintion cannot suddenly have two parameters:
    
    
        cout <<"enter a score" << endl;
    
        while ( score != -100 )
        {
            sum += score;
            NumScores++; 
            cout << "Enter a test score ( 0 to quit ): "; 
            cin >> score; 
        }
    
    
        return sum/NumScores;
    
    }
    
    int main()
    {
        Average Numbers;
        //Average.findaverage();
        //You declared a variable named Numbers of type Average, so Numbers is your variable name.  
        //It's similar to when you declare a variable like this: int num;
        //You wouldn't then do this: int = 10;
    
        //You can declare a variable to store the average.  The type of the variable has to be the
        //same type as the return type of the function.
        float avg = Numbers.findaverage();
        
        cout <<"The average is " << avg <<endl;
        return 0;
    }
    When no one helps you out. Call google();

  11. #11
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    Your logic loop:
    Code:
    cout <<"enter a score" << endl;
    
    while ( score != -100 )
    {
            sum += score;
            NumScores++; 
            cout << "Enter a test score ( 0 to quit ): "; 
            cin >> score; 
    }
    A logic loop that works

    Code:
     cout << "Enter a test score ( 0 to quit ): "; 
    cin >> score;
    
    while ( score != -100 )
    {
         sum += score;
         NumScores++; 
         cout << "Enter a test score ( 0 to quit ): ";     
         cin >> score;
    }
    See the difference?
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  12. #12
    Registered User
    Join Date
    Mar 2004
    Posts
    494
    yep thanks for pointing that out.
    When no one helps you out. Call google();

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you Initialize all classes once with New?
    By peacerosetx in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2008, 10:47 AM
  2. Multiple Inheritance - Size of Classes?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 11-26-2004, 09:04 AM
  3. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  4. Exporting VC++ classes for use with VB
    By Helix in forum Windows Programming
    Replies: 2
    Last Post: 12-29-2003, 05:38 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM