0

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
1
  • You literally asked it to do that. Commented May 30, 2015 at 4:15

3 Answers 3

4
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();
}

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.