Hi everybody,
i was writing a small c++ class that uses a list as a data member , i then wrote a small print function to print the numbers in the list

#include <iostream>
#include <string>
#include <sstream>
#include <list>
using namespace std;
class A
{
private:
	list<int> number;
	string ConverttoS(int) const;
public:
	A();
	string print();
};

string A::ConverttoS(int input) const
{
	std::stringstream out;
	out << input ;
	return out.str();
}

string A::print() 
{
	string output = "";
	list<int>::iterator i;

	for(i = number.begin() ; i != number.end() ; ++i)
		output =  output + ConverttoS(*i);

	return output;
}

everything is working fine until i decided to set the print member function as a const , since it is not modifying anything and it is only calling const data members but when i did that , the compiler gave the following error:

error C2679: binary '=' : no operator defined which takes a right-hand operand of type 'class std::list<int,class std::allocator<int> >::const_iterator' (or there is no acceptable conversion)

error C2679: binary '!=' : no operator defined which takes a right-hand operand of type 'class std::list<int,class std::allocator<int> >::const_iterator' (or there is no acceptable conversion)

it is not a big deal i can simply remove the const keyword from the implementation and declaration and everthing will work fine , but i am only curious to know why this is happening

This is simple (I hope). You are using an iterator. The iterator allows the method to change the data.

Now since an iterator is a class and your compiler cannot know until link time that the iterator does not change the data, you compiler HAS to assume that the iterator does, hence it doesn't allow const to be added to print.


A simple way to get round this is to use const_iteraror.

Another way is this

std::string
A::print() const
{
   std::ostringstream oSS;
   copy(number.begin(),number.end(),
          std::ostream_iterator<int>(oSS,""));
    return oSS.str();
}

The later method avoids the convert to S construction that creates a number of stringstreams, and avoids having an explicit iterator. So is slightly more preferable to some peoples tastes.

Note: you have to add #include <iterator> , to your C++ file.

i tried to do this but i could not it is giving me an error

Can you post your new non-compiling/non-running code please.

The only thing that I can think you might have done wrong is to forget to at const to both the declaration and the instance eg.

class A
{
    std::string print() const ; 
};

std::string
A::print() const
{
   std::string output;
    std::list<int>::const_iterator iterI;
  //...
   return output;
}

yes that was the problem , it worked fine thanks alot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.