initializing a value in a class?

I want to assign a private int to 250 and a public function to be able to call for the value of that private value. How can I do this? Here is what I have, hopefully someone can see where I am trying to go with this and help me out:
1
2
3
4
5
6
7
8
9
10
11
12
13
class bruteForce{

public:
int getHP()
{
return hp;
}
	
private:
int hp = 250 ;

};

how can I call the "250"
You need to make a ctor.

2 ways... you can put initialzation in the ctor body:


1
2
3
4
5
6
7
8
9
10
11
class bruteForce
{
public:
  // constructor
  bruteForce()
  {
    hp = 250;
  }

//...
};


or you can use the ctor's initializer list:

1
2
3
4
5
6
7
8
9
10
11
class bruteForce
{
public:
  // constructor
  bruteForce()
   : hp(250)
  {
  }

//...
};
oh ok, so I can't acutally assign values directly inside the private part of the class then?
yea you can, what errors are you getting?

............code....

EDIT: sorry I got that wrong, you can have const static ints declared, but not static ints, or ints. like Disch said above you can simply declare in constructor.
eg this will work...:

xxx.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#ifndef XXX_H_
#define XXX_H_

#include <iostream>
#include <string>
using namespace std;

class MyClass
{
  public:
    const static int ZSIZE=100;
    int hp;
  private:
    const static int BBSIZE=666;
    int ph;
};

#endif  


xxx.cpp
1
2
3
4
5
6
7
8
9
10

#include "xxx.h"

MyClass::MyClass()
{
    hp=78787;
    ph=909090;
}

// etc functions... 
Last edited on
Notice that the initializer list is better than calling the = operator in the constructor body,
- In C++0x that should be possible http://www2.research.att.com/~bs/C++0xFAQ.html#member-init -
Topic archived. No new replies allowed.