Natalie Ng
Natalie Ng

Reputation: 11

Static int with array C++

I'm trying to static count my driver user. however it always give me same value instead

class Driver {
private:
  static int ID;
  string name;
public : 
  void displayDriver(string n) {
    cout << ID << endl;
  }
  void createDriver(string n) {
    name = n ;
    ID++;
  }
}

int Driver::id=0;

int main() {
  Driver driver[10];
  Driver[0].createDriver("first");
  Driver[1].createDriver("second");
  Driver[2].createDriver("first");                 
  Driver[0].displayDriver();
  Driver[1].displayDriver();
  Driver[2].displayDriver();
}

my expected output should be :

 1
 2
 3

but system shows me :

 3
 3
 3

Upvotes: 0

Views: 133

Answers (3)

Shivam
Shivam

Reputation: 457

It is because the value of ID gets incremented each time u createDriver("");

(no matter for which Driver[]) as it is a static variable

So u r incrementing ID progressively to 3 in first 3 lines while displaying value of ID in next 3 lines

To get the expected output

I think u need to try it like this :

 Driver[0].createDriver("");
 Driver[0].displayDriver();
 Driver[1].createDriver("");
 .
 .  
 .

So on!

Note that all drivers have the same ID (static field).

Upvotes: 0

gae123
gae123

Reputation: 9457

Do something like I show here to get the results you expect. The idea is to keep the next counter in ID but every instance to have its own id that get initialized when you create the driver.

class Driver
{
  private:
     static int ID;
     int my_id;
     string name;
  public : 
  void displayDriver(string n)
  {
   cout << my_id << endl;
  }
  void createDriver(string n)
  {
    name = n ;
    my_id = ID++;
  }
}
int Driver::id=0;
int main
{
  Driver driver[10];
  Driver[0].createDriver("first");
  Driver[1].createDriver("second");
  Driver[2].createDriver("first");                 
  Driver[0].displayDriver();
  Driver[1].displayDriver();
  Driver[2].displayDriver();
}

Upvotes: 1

LeleDumbo
LeleDumbo

Reputation: 9340

private:
 static int ID;

Denotes that ID is shared among Driver instances. Any change to it (from createDriver in your current code) will be reflected in ALL instances. Don't use static field if you want each instance has its own unique field.

Upvotes: 4

Related Questions