OOP class design in C++ -


i have simple question class design in c++.

lets assume have following class:

class database {     public:         database();           void addentry(const std::string& key, double value);         double getentry(const std::string& key);      protected:         std::map<std::string, double> table; }; 

there class holds pointer instance of database class:

class someclass {     protected:         database *somedatabase; }; 

here confused, 2 options come mind:

  1. each instance of someclass have database of own. in sense data added instance present in database (dedicated databases).
  2. each instance of someclass referring central database. data added of instances of someclass in 1 single database (a global database).

question:

  • what name of aforementioned concepts in oop?
  • how each of aforementioned approaches can achieved in c++

what looking topic of ownership in c++. when ownership, mean responsible managing memory holds object.

in first example each someclass could own own database.

class someclass {     private database *db;     public someclass();     public someclass(database* db);     public ~someclass(); }  someclass::someclass() {     this.db = new database(); }      someclass::someclass(database* db) {     this.db = db; }  someclass::~someclass() {     delete this.db; } 

this someclass either takes ownership of database given or creates own (practically 1 or other). means can pass in database object (using concept known dependency injection):

database *db = new database(); someclass sc(db); sc.dosomestuffwithdb(); 

or let class create database object:

someclass sc(); sc.dosomestuffwithdb(); 

in above example don't have worry disposal of database objects, knowing someclass should take care of disposal in destructor.

in other scenario share database without having disposed of someclass (whether it's global or not irrelevant).

class someclass {     private database *db;     public someclass(database* db); }  someclass::someclass(database* db) {     this.db = db; } 

here pass multiple someclass objects same database , not have worry them being disposed of of objects.

database *db = new database(); someclass *sc1 = new someclass(db); someclass *sc2 = new someclass(db); sc1.dosomestuffwithdb(); delete sc1; sc2.dosomestuffwithdb(); delete sc2; delete db; 

in scenario able reuse database object before disposing of external our someclass objects. practically speaking, disposal managed class databasestore, allowing have reliable way handle , reuse database objects.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -