Problem with const reference as a parameter

A

Aggro

Short question is here:
I would like to have the code below to compile, without having to remove
the "const" from it, can anyone help?

(More explanation can be found at the end of the message if that is needed)

---------code.cpp-------------
#include <sstream>
#include <iostream>

class ValueHolder
{
private:
unsigned int value;

public:
ValueHolder()
{
value = 40;
}

std::string ReturnValueAsString()
{
std::eek:stringstream oss;
oss << value;
return oss.str();
}
};

void PrintValue( const ValueHolder &holder )
{
std::cout << holder.ReturnValueAsString() << std::endl; // Line 25
}

int main()
{
ValueHolder holder;
PrintValue( holder );

return 0;
}

---------code.cpp-------------

-------Error message----------
C:\code.cpp(25) : error C2662: 'ReturnValueAsString' : cannot convert
'this' pointer from 'const class ValueHolder' to 'class ValueHolder &'
Conversion loses qualifiers
-------Error message----------



I have a function that looks like this:
void PrintValue( const ValueHolder &holder )
{
std::cout << holder.ReturnValueAsString() << std::endl;
}

But it doesn't work. It works, if I remove the const, or it works if I
remove the holder.ReturnValueAsString() from it. It would also work if I
add public: std::string str; to the ValueHolder class, set a value for
it and call it from function like this: holder.str

But that is difficult in my real situation, because I have a class where
I have many variables and they change often. So I would prefer the
possibility to create a string using std::eek:stringstream and then
returning the result from that from my class.

And I would like to have it so that I can use the reference of the class
as a const in my functions.
 
D

Daniel T.

Aggro said:
Short question is here:
I would like to have the code below to compile, without having to remove
the "const" from it, can anyone help?

(More explanation can be found at the end of the message if that is needed)

---------code.cpp-------------
#include <sstream>
#include <iostream>

class ValueHolder
{
private:
unsigned int value;

public:
ValueHolder()
{
value = 40;
}

std::string ReturnValueAsString()

make the above line:

std::string ReturnValueAsString() const
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top