Leandro
Leandro

Reputation: 183

consts inside classes?

Hi I was trying to define a constant inside a class, doing it the normal or usual way doesnt seem to work

class cat
{
public:

    cat();
    ~cat();


private:

    static const int MAX_VALUE = -99999;
    int Number;


public:

    void OrganizeNumbers();
    void SetNumbers();

};

So the solution I found after doing some research was to declare it as static but what does this means and also I want to ask it is really necesary to declare a constant, becuase as you can see it is private right? i means it can only be accessed by the class methods so why to set a constant and also I read that using static only allows you to use integral type so its actually a dissavantage... if you are thinking to make a game.

Upvotes: 0

Views: 114

Answers (4)

Hicham
Hicham

Reputation: 979

you have to init the const attribute in the constructor with :

cat() : MAX_VALUE(-99999) {}

(which was declare as const int MAX_VALUE;)

Upvotes: 0

Filip Roséen
Filip Roséen

Reputation: 63902

static means that the member will be shared across all instances of your object.

If you'd like to be able to have different values of a const member in different instances you'll need to use a initialization list to set it's value inside your constructor.

See the following example:

#include <string>

struct Person {
  Person (std::string const& n) 
    : name (n)
  {
    // doing: 'name = n' here is invalid
  }

  std::string const name;
};


int main (int argc, char *argv[]) {
  Person a ("Santa Claus");
  Person b ("Bunny the Rabbit");
}

Further reading

Upvotes: 3

Paul Butcher
Paul Butcher

Reputation: 6956

There seems to be some confusion of ideas here:

  1. A static member doesn't have to be an integral type, the disadvantage you mention does not exist.
  2. const and private are unrelated, just because a member can only be accessed from instances of a given class, doesn't mean that nothing is going to change it.

Being const-correct guards against runtime errors that may be caused by a value changing unexpectedly.

Upvotes: 1

paulsm4
paulsm4

Reputation: 121881

1) Declare it "private" if you're only going to use MAX_VALUE inside your class's implementation, declare it under "public" if it's part of your class's interface.

2) Back in "C" days, "static" was used to "hide" a variable from external modules.

There's no longer any need to do this under C++.

The only reason to use "static" in C++ is to make the member class-wide (instead of per-object instance). That's not the case here - you don't need "static".

3) The "const" should be sufficient for you.

4) An (older-fashioned) alternative is to define a C++ enum (instead of a "const int")

Upvotes: 2

Related Questions