I encounter a problems about override virtual functions, in fact,it is about hessian (a web service protocol).
it has a base class Object, and some derived classes : Long,Int,String,…,all derived classes has a no-virtual function “value”
class Object
{
...
};
class Long :public Object
{
...
public:
typedef long long basic_type;
basic_type value(){return value_;}
private:
basic_type value_;
...
};
class Int :public Object
{
...
public:
typedef int basic_type;
basic_type value(){return value_;}
private:
basic_type value_;
...
};
now I want to add a function ,say, toString ,which can convert Object to a string:
Object *obj = ...
cout<<obj->toString();
if I can change the value function to virtual ,I only need to write a toString function in Object, else, I need to write a virtual function toString, and to override this functions in all derived classes.
for example
class Object
{
virtual Type value(); // It seemed that I can't write a function like this,because the Type is different for different derived classes
std::string toString()
{
some_convert_function(value());
}
};
but I can’t write a virtual value function because of return value can’t be override.
is there any good solution for this issue?
Thanks
No, you can’t write toString in Object using a virtual ‘value’ function and override the return type. However you can write a virtual toString and with a template programming trick accomplish almost the same thing.