简体   繁体   中英

Overriding a base class function with different return types

I have a 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 as Int, Bool, String etc. For 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 a method named getVal() that returns a different type (bool, int, etc.). I want to allow polymorphic behavior for Variable class.
I tried: void getVal(); which seemed wrong and the compiler showed an error: shadows Variable::getVal() which sounds bad. I thought of using template <typename T> T getVal(); but it didn't help.

Any suggestions? Do I have to use casting for that?

Many thanks...

You can't overload by return type . I think that a template would work better in your case. There's no need for 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 would be 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';

The types are determined in compile time. So no amount of polymorphism will allow you to change the return type.
Virtual dispatch is done at runtime, but the types of the methods and object must be correct and the same in compile time.

If you just need to print the value, just add virtual ToString() method. Or even make i templated if you don't want to write it again for each derived type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM