c++ - Overriding a base class function with different return types -


i have base class named variable:

class variable { protected:     std::string name;    public:     variable(std::string name="");     variable (const variable& other);     virtual ~variable(){}; }; 

i have several derived classes, such int, bool, string etc. example:

class bool: public variable{ private:     bool value;  public:     bool(std::string name, bool num);     ~bool();     bool (const bool& other);     bool getval(); 

each derived class has method named getval() returns different type (bool, int, etc.). want allow polymorphic behavior variable class.
tried: void getval(); seemed wrong , compiler showed error: shadows variable::getval() sounds bad. thought of using template <typename t> t getval(); didn't help.

any suggestions? have use casting that?

many thanks...

you can't overload return type. think template work better in case. there's no need polymorphism or inheritance here:

template<class t> class variable { protected:     t value;     std::string name;    public:     variable(std::string n, t v);     variable (const variable& other);     virtual ~variable(){};     t getval(); }; 

the usage pretty simple:

variable<bool> condition("name", true); variable<char> character("name2", 't'); variable<unsigned> integer("name3", 123); std::cout << condition.getval() << '\n'; std::cout << character.getval() << '\n'; std::cout << integer.getval() << '\n'; 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -