c++ - Use polymorphism with references. Invalid initialisation of non const reference -


i use polymorphism references, without new operator. there 1 baseclass, has (in case one) virtual method. , subclasses implement it.

i've created factory function, creates appropriate instance. error:

invalid initialization of non-const reference of type 'baseclass&' rvalue of type 'subone' 

the code is:

#include <iostream>  class baseclass { public:     virtual void run() = 0; };  class subone : public baseclass { public:     virtual void run() override {         std::cout << "i subone!" << std::endl;     } };  class subtwo : public baseclass { public:     virtual void run() override {         std::cout << "i subtwo!" << std::endl;     } };  baseclass& basefactory(int num) {      switch(num) {          case 1:             return subone();          case 2:         default:             return subtwo();      }  }  void executer(baseclass& base) {      // code...      base.run();      // code...  }  int main() {      baseclass& base = basefactory( 1 );      // code...      executer(base);      return 0; } 

you cannot return locally-created object function returns reference:

baseclass& basefactory(int num) {     ...     return subone(); // not allowed } 

this because local object goes out of scope function over, , end hanging reference.

you should change function returning dynamically-allocated object, , storing smart pointer:

baseclass* basefactory(int num) {     ...     return new subone(); }  unique_ptr<baseclass> dyn { basefactory(1) }; 

Comments