class - C++ Getting an object -


lets have following class:

static int counter = 0;  class account { public:    int id;    int favnumber;     account(int favnum) {       this->id = ++counter;       this->favnumber = favnum;    } };  account user1(4); account user2(9); 

now both accounts user1 , user2 have different id unique. there way knowing id of account field of object "favnumber", if how should implemented?

something getfieldbyid(int id)

you may use std::map :

#include <map>  class account {    // make attributes private. better practice    int id;    int favnumber;     static int s_counter;  //^^^^^^^^^^^^^^^^^^^^^ better move static private member of account  public:     account(int favnum) {       this->id = ++s_counter;       this->favnumber = favnum;    }     // getters    int getfavnumber() const { return favnumber; }    int getid() const { return id; } };  int account::s_counter = 0; // ^^^^^^^^^^^^^^^^^^^^^^^^ don't forget initialize  account user1(4); account user2(9);  std::map<int, account*> accounts; accounts[user1.getid()] = &user1; accounts[user2.getid()] = &user2;  // favnum id : accounts[id]->getfavnumber(); 

but technique, sure pointers still valid ! if not, have bad surprises ...


what have done in previous code ?

  • we passed attributs in private (better practice).
  • we created getters access them.
  • we passed counter static variable static private member of account.
  • we used std::map have listing of accounts created , keys ids of accounts.

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -