c++ - OO design, table design -


design table wood or steel meterial. have following designed, better , why? or better suggestion design?

design 1 :

class meterial{ public:   void virtual info()=0; };  class wood:public meterial{ public:   void info(); };  void wood::info(){   cout<<"wood"<< " "; }  class steel:public meterial{ public:   void info(); };  void steel::info(){   cout<<"steel"<< " "; }     class furniture{   void virtual info()=0; };  class table:public furniture{ private:   meterial * _meterial; public:   table(meterial * m);   void info(); };  table::table(meterial * m){   _meterial= m; }   void table::info(){   _meterial->info();   cout<< " table " << endl; }  int main(){   table * wood_table=new table(new wood());   table * steel_table=new table(new steel());   wood_table->info();   steel_table->info(); } 

design 2:

class meterial{ public:   virtual void info()=0; };  class wood:public meterial{ public:   void info(); };  void wood::info(){   cout<<" wood " << " "; }  class steel:public meterial{ public:   void info(); };  void steel::info(){   cout<<" steel " << " "; }    class furniture{ public:   virtual void info()=0; };  class table:public furniture{ public:   void info(); };  void table::info(){   cout<<" table "<< endl; }  class woodtable:public wood,public table{ public:   void info(); };  void woodtable::info(){   wood::info();   table::info(); }   class steeltable:public steel,public table{ public:   void info(); };  void steeltable::info(){   steel::info();   table::info(); }    int main(){   woodtable *woodtable = new woodtable();   steeltable *steeltable = new steeltable();    woodtable->info();   steeltable->info(); } 

thanks!

you should use inheritance when have specific reason to, or when other options not better nor worse. never inherit reuse.

does material have behaviour can change dynamically? can table's material change @ runtime? if answer yes either of these you'll need runtime polymorphism , inheritance. first design step in right direction. second design, however, risky , brings little table (and pardon pun). multiple inheritance? why? should have specific, solid reason use multiple inheritance.

another design alternative use compile-time polymorphism.

struct wood { }; struct steel { };  template<class m> struct table { };  // ... table<wood> wood_table; 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -