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:
- each instance of
someclass
have database of own. in sense data added instance present in database (dedicated databases). - each instance of
someclass
referring central database. data added of instances ofsomeclass
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
Post a Comment