Thread: classes and functions

  1. #1
    Registered User
    Join Date
    Dec 2007
    Location
    Rochester
    Posts
    40

    classes and functions

    I just remade a program that uses a class for the user and a class for an enemy, I was testing the class system to see if I could make a good one. But it ended up not working. The compiler is complaining about "was expecting ; before "." operator practically everywhere I reference a function within a class.

    Here is a sample, I lost the original in the depths of my flash drive, but this is as near as I can remember it:
    Code:
    class zombie {
    	public:
    
    	zombie ( void ) {
    		hp = 100;
    	}
    	~zombie {}
    	void attack ( void ) {
    		//determines attack based on a random integer
    		//references player class's attack function
    		//returns the creatures attackpower to the player's takedamage function
    	}
    	void takedamage ( dmg ) {
    		//sets hp to a value based on defense and dmg taken
    	}
    
    	private:
    
    	int bite ( void ) {
    		//displays something for the user to see that the zombie attacked
    		//displays damage the zombie did
    		//returns attackpower
    	}
    	int gnaw ( void ) {
    		//does the same as above
    	}
    	int noattack ( void ) {
    		//displays something informing the user that the zombie failed to attack
    		//returns 0
    	}
    	int attackpower;
    	int attacktype; //to store the number that determines the attack the zombie will do
    	int hp;
    };
    
    class player {
    	//same as above, only with selectable attacks
    	public:
    
    	player ( void ) {
    		hp = 100;
    	}
    	~player {}
    	int attack ( void ) {
    		//allows player to select from a list of attacks, then uses that attack
    		//returns the attackpower of the attack chosen to the zombie's takedamage function
    	}
    	void takedamage ( dmg ) {
    		//sets hp to a value based on defense and dmg taken
    	}
    
    	private:
    
    	int axe ( void ) {
    		//displays text about what the attack did
    		//returns the attackpower
    	}
    	int shotgun ( void ) {
    		//does the same as above
    	}
    	int chainsaw ( void ) {
    		//does the same above
    	}
    	int attackpower;
    	int attacktype; //to store the number that determines the attack the zombie will do
    	int hp;
    };
    
    void battle ( void ) {
    	player player;
    	zombie bob;
    	while (player.hp > 0 and bob.hp > 0) {
    		if (bob.hp > 0) {
    			bob.attack();
    		}
    		if (player.hp > 0 ) {
    			player.attack();
    		}
    	}
    	if (player.hp <= 0) {
    		cout << "you lost";
    		exit (1);
    	}
    	if (bob.hp <= 0) {
    		cout << "you won";
    	}
    }
    
    int main() {
    	cout << //blablabla, set up scenario
    	battle ();
    }
    everywhere I use player.anything or bob.anything it says it was expecting a ; before bob, '.', and anything. I think its complaining about me not having created the classes before I used them, but I'm not sure.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Code:
    //cout << //blablabla, set up scenario

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Your code has a number of errors, such as
    Code:
    ~zombie() {}
    (If you are not going to put anything in the destructor, you don't even need to declare one.)

    Code:
    void takedamage ( dmg )
    This and similar is not how you declare functions.

    Code:
    player player;
    This doesn't look good but didn't produce an error. However, it is not a good idea to have a type and a variable named the same. A good convention is to start class names with an uppercase character. Then you could write:
    Code:
    Player player
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    OK, so errors...

    Code:
    ~zombie() {}
    ~player() {}
    Forgot parameter list.

    Code:
    void takedamage ( int dmg )	
    void takedamage ( int dmg ) {
    dmg is not a type! Type is missing too - put int before.

    Code:
    while (player.hp > 0 and bob.hp > 0) { // Error: hp is private
    if (bob.hp > 0) { // Error: hp is private
    if (player.hp > 0 ) { // Error: hp is private
    if (player.hp <= 0) { // Error: hp is private
    if (bob.hp <= 0) { // Error: hp is private
    hp is a private member; cannot access directly.

    Code:
    int attack ( void ) {
    	return 0;
    }
    Must return a value.

    You also specify a lot of (void) which is not necessary in C++. You can just do (). Same thing. Looks better too.

    Although Player player looks better, I still recommend you put a C into class names - so Player becomes CPlayer instead; it suggests CPlayer is actually a class and not to be confused with a variable name. Especially in this example.
    Last edited by Elysia; 12-17-2007 at 12:34 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Although Player player looks better, I still recommend you put a C into class names - so Player becomes CPlayer instead; it suggests CPlayer is actually a class and not to be confused with a variable name. Especially in this example.
    I think that is only necessary if the naming convention has other uses for capitalised names, e.g., function names. Otherwise the 'C' prefix becomes just a distraction.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    This can be debated, but it also tells you that "Player" is a class and not something else and you won't confuse player or Player with CPlayer.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    This can be debated, but it also tells you that "Player" is a class and not something else and you won't confuse player or Player with CPlayer.
    What else can it be confused with? At a glance it is clear that "Player" is a class, just as it is clear that "CPlayer" is a class. After all, naming conventions are about sensible consistency.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    At glance, it's not clear Player is a class; it can be a struct (read: just a big block of data members) or a typedef. I also feel it's better to separate type from name. Just as you say player player is bad, I feel Player player is bad too - they're virtually the same aside from an upper case P.
    Anyway, it's not an important detail. I suppose it's a minor coding-style detail.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    At glance, it's not clear Player is a class; it can be a struct (read: just a big block of data members) or a typedef.
    That depends on the naming convention. anon merely stated: "good convention is to start class names with an uppercase character."

    Nonetheless, it may actually be better to have the same naming convention for non-POD classes, POD structs and typedef names... but I think that's a discussion for another thread.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Dec 2007
    Location
    Rochester
    Posts
    40
    Thanks for all the help, I really appreciate it. I'm kinda new to this so its a little confusing

  11. #11
    Registered User
    Join Date
    Dec 2007
    Location
    Rochester
    Posts
    40
    Elysia said:
    Code:
    Code:
    int attack ( void ) {
    	return 0;
    }
    
    Must return a value.
    does that mean i can't return 0?

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I added return 0 because you didn't return anything. Any value is fine, as long as it's an int.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    Dec 2007
    Location
    Rochester
    Posts
    40
    ok, thanks for the help

  14. #14
    Registered User
    Join Date
    Dec 2007
    Location
    Rochester
    Posts
    40
    Ok, I made at least a test of the program, and my compiler seems to hate me, I don't see any problems with the code, but it does:

    I know I'm not supposed to post all my code, but I'm still getting the same types of problems

    Code:
    #include <iostream>
    #include <windows.h>
    #include <cstring>
    #include <time.h>
    using namespace std;
    
    void randomize () {
        time_t seconds;
        time(&seconds);
        srand ((unsigned int) seconds);
    }
    
    void clrscrn ( void ){
      DWORD n;                         /* Number of characters written */
      DWORD size;                      /* number of visible characters */
      COORD coord = {0};               /* Top left screen position */
      CONSOLE_SCREEN_BUFFER_INFO csbi;
    
      /* Get a handle to the console */
      HANDLE h = GetStdHandle ( STD_OUTPUT_HANDLE );
    
      GetConsoleScreenBufferInfo ( h, &csbi );
    
      /* Find the number of characters to overwrite */
      size = csbi.dwSize.X * csbi.dwSize.Y;
    
      /* Overwrite the screen buffer with whitespace */
      FillConsoleOutputCharacter ( h, TEXT ( ' ' ), size, coord, &n );
      GetConsoleScreenBufferInfo ( h, &csbi );
      FillConsoleOutputAttribute ( h, csbi.wAttributes, size, coord, &n );
    
      /* Reset the cursor to the top left position */
      SetConsoleCursorPosition ( h, coord );
    }
    
    class zombie {
        public:
        zombie ( int hp ) {}
        ~zombie () {}
        int life () {
            if ( hp > 0 ) {
                return 1;
            }
            if (hp <= 0 ) {
                return 0;
            }
        }
        void attack () {
            attacktype = rand () % (2) + 1;
            if (attacktype = 1) {
                gnaw();
            }
            if (attacktype = 2) {
                bite();
            }
            if (attacktype = 3) {
                moan();
            }
            cin.get();
            clrscrn();
        }
        void takedamage ( int dmg ) {
            hp = hp - dmg;
            cout << "The zombie took " << dmg << " damage.";
            cout << "\n\nThe zombie's health is down to " << hp;
            cin.get();
            clrscrn();
        }
        private:
        int hp, attacktype, attackpower, dmg;
        void gnaw () {
            attackpower = rand () % (5) + 1;
            cout << "The zombie gnaws on your arm, trying to extract you life force";
            cout << "You take " << attackpower << " damage";
            user.takedamage (attackpower);//'user' undeclared (first use this function)
        }
        void bite () {
            attackpower = rand () % (11) + 10;
            cout << "The zombie bites your face, trying to extract you brains";
            cout << "You take " << attackpower << " damage";
            user.takedamage (attackpower);//'user' undeclared (first use this function)
        }
        void moan () {
            cout << "The zombie moans loudly, waking the neighbors.\n, then a small music video begins with the lyrics to 'lets wake up the neighbors'";
        }
    }
    
    class player {
        public:
        player ( int hp ) {}//invalid use of member (did you forget the '&' ?
        ~player () {}
        int life () {
            if ( hp > 0 ) {
                return 1;
            }
            if (hp <= 0 ) {
                return 0;
            }
        }
        void attack () {
            cout << "Please enter the weapon you would like to use:\n\n"
                 << "1. Axe\n"
                 << "2. Machete\n"
                 << "3. Chainsaw\n";
            cin >> attacktype;
            switch (attacktype) {
                case 1:
                axe();
                break;
                case 2:
                machete();
                break;
                case 3:
                chainsaw();
                break;
                default:
                cout<<"Your instincts have failed you, and you freeze up\n";
                break;
            }
            cin.get();
            clrscrn();
        }
        void takedamage ( int dmg ) {
            hp = hp - dmg;
            cout << "You took " << dmg << " damage.";
            cout << "\n\nYour health is down to " << hp;
            cin.get();
            clrscrn();
        }
        private:
        int hp, attacktype, attackpower, dmg;
        void axe () {
            attackpower = rand () % (25) + 1;
            cout << "You swing the axe at the zombie's head, but it continues to move\n";
            cout << "The zombie takes " << attackpower << " damage";
            bob.takedamage (attackpower);//'bob' undeclared (first use this function)
        }
        void machete () {
            attackpower = rand () % (25) + 25;
            cout << "You hack down the zombie with the machete\n";
            cout << "The zombie took " << attackpower << " damage";
            bob.takedamage (attackpower);//'bob' undeclared (first use this function)
        }
        void chainsaw () {
            attackpower = rand() % (26) + 50;
            cout << "You zwing your chainsaw, annihilating the zombie's limbs";
            cout << "The zombie took " << attackpower << " damage";
            bob.takedamage (attackpower);//'bob' undeclared (first use this function)
        }
    }
    
    void battle () {//new types may not be defined in a return type // two or more data types in declaration of 'battle' [it says that one twice]
        zombie bob;//no matching function call for 'zombie::zombie()' //candidates are zombie::zombie (const zombie&), and 'zombie::zombie(int)'
        player user;//same as above only 'player::player()'
    
        while (bob.life() == 1 and user.life() == 1) {
            if (user.life() == 1) {
                user.attack();
            }
            if (bob.life() == 1) {
                bob.attack();
            }
        }
        if (user.life() == 0) {
            cout << "You failed to defeat the zombie\n\n";
        }
        if (bob.life() == 0) {
            cout << "You defeated the zombie\n\n";
        }
    }
    
    int main() {
        cout << "blablabla, battle the zombie\n";
        cin.get();
        clrscrn();
        battle();
        cin.get();
        cout << "closing game, this is only a test";
    }
    I really wish all these little phrases had a little more description to them on the compiler's website

    Sorry about all the code, I hope it's easy to read

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You need semicolons at the end of your member function declarations (e.g. gnaw, bite, etc) - by that, I mean after the last brace.

    Try to develop just a few lines before compiling. It helps when it comes to "remembering which change caused what problem".

    Another tip is "fix the first error, then recompile", because quite often, you get one error that gets the compiler confused, and "everything is wrong from there on", so you have ONE missing semicolon, and the compiler spews out 300 errors.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Classes being able to use other classes functions
    By rainmanddw in forum C++ Programming
    Replies: 6
    Last Post: 01-29-2006, 11:19 AM
  2. Functions and Classes - What did I do wrong?
    By redmage in forum C++ Programming
    Replies: 5
    Last Post: 04-11-2005, 11:50 AM
  3. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  4. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM