-
toString() const string&
I've a variable called val of Type Var.
Var Class have a tostring() methods that returns const string& type.
But When I compile it compiler is firing this Error on the following line.
Code:
key+"="+val.toString()+"; at=";
Code:
error: passing ‘const Var’ as ‘this’ argument of ‘const std::string& Var::toString()’ discards qualifiers
Code of toString() method
Code:
const string& Var::toString(){
return (const string&)__data;//__data is of type string (just string not a reference or a const)
}
-
don't return a const type, that doesn't make sense here. Why do you return a reference and not just an object?
Const-correctness is something that applies to arguments of functions, not of their return types. Remember: try to avoid declaring variables as 'const' (like in a class).
Code:
string Var::toString()
{
return static_cast<string>(__data);
}
A nice example why you should use C++ style casts : what does '(const string&)__data' do?
-
This function should be declared as const (because it returns data and doesn't modify it), otherwise you can't call it on constant instances. E.g:
Code:
void foo(const Var& v)
{
v.toString(); //discards qualifiers error, unless toString is a const method
}
As to casts:
if you want to return a reference, you don't need a cast. This is how you normally make a reference to something (i doesn't have to be a reference for a reference to refer to it):
Code:
int i = 42;
int& ref = i; //note: no cast!
If __data is a std::string then casting it to std::string is meaningless.
I seem to remember that you had other rather meaningless casts in your code, such as:
If it didn't already work without that cast (because Var has a non-explicit constructor that takes an integer argument), then the cast wouldn't do the right thing either. Normal ways to declare and initialize an instance:
Code:
Var x(42);
Var x = 42; //if the constructor is not explicit
Var x = Var(42); //copy from a temporary
-
@annon
exactly it fixed after I changed it to
Code:
const string& toString() const{
//
}
Thanks