problem with classes

im using dev c++ and i keep getting an error for this.

class pokemon
{
public:

int bhp;
);

pokemon bulbasaur;

bulbasaur.bhp = 45;

it is saying that the code "bulbasaur.bhp = 45;" is not correct. the error code is "error:expected contsructor, destructor, or type conversion before '.' token".
I dont see a problem with that, unless you declare and call

1
2
3
pokemon bulbasaur;

bulbasaur.bhp = 45;


somewhere outside either main() or otherfunction()
Yea, it sounds like you wrote bulbasaur.bhp = 45; outside of a function, which is a syntax error, as only declarations and definitions of classes, functions, ... go out there. If you want this pokemon to start with some bhp value use a constructor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class pokemon
{
 private:
    int bhp; //This should be private (i.e. it should not be directly modified from outside this class.)

 public:
    pokemon(int hp) : bhp(hp) {} //initialize bhp to whatever is passed to the construtor

    int getHp() { return bhp; } //accessor method: now you're able to read bhp from outside the class.
};

//...
#include <iostream>

using namespace std;

int main() {
    //...
    pokemon bulbasaur(45); //now bulbasaur has 45 hp
    cout << balbasaur.getHp() << endl; //print balbasaur's hp to the standard output
    //...
}
Topic archived. No new replies allowed.