what's wrong with this code in VC++ 2008 Ex

#include <conio.h>
#include <iostream>
using namespace std;

class Allocate
{
private:

	void* v;
	unsigned n;
	__int8 dummy_ret;

	void* Alloc(unsigned& n)
	{
		void* ret;
		if(n == 0)
			ret = 0;
		else
		{
			ret = new(nothrow) char[n];
			if(ret == 0)
				n = 0;
		}
		return ret;
	}

	void Free()
	{
		if(n != 0)
			delete [] v;
		n = 0;
	}

public:
	unsigned GetSize()
	{
		return n;
	}

	void SetSize(unsigned size)
	{
		SetData(v,size);
	}

	void* GetData()
	{
		return v;
	}

	void SetData(void* data,unsigned size)
	{
		if(size == 0)
			return;
		char* w = (char*)Alloc(size);
		for(unsigned i = 0; i < size; i++)
			w[i] = ((char*)data)[i];
		Free();
		v = w;
		this -> n = size;
	}

	__int8& operator [](unsigned i)
	{
		if(i < n)
			return ((char*)v)[i];
		else
			return dummy_ret;
	}

	Allocate& operator =(const Allocate& a)
	{
		SetData(a.GetData(),a.GetSize());
		return *this;
	}

	Allocate& operator ++()
	{
		SetSize(GetSize() + 1);
		return *this;
	}

	Allocate(unsigned n)
	{
		v = Alloc(n);
		this -> n = n;
	}

	Allocate(void* w,unsigned size)
	{
		n = 0;
		SetData(w,size);
	}

	Allocate(const Allocate& a)
	{
		*this = a;
	}

	~Allocate()
	{
		dummy_ret = 0;
		Free();
	}
};

int main()
{
	Allocate a("hello",6);
	cout<< a[0];
	_getch();
}

Error 1 error C2662: 'Allocate::GetData' : cannot convert 'this' pointer from 'const Allocate' to 'Allocate &' g:\important files\my documents\borland studio projects\console.cpp 72
Error 2 error C2662: 'Allocate::GetSize' : cannot convert 'this' pointer from 'const Allocate' to 'Allocate &' g:\important files\my documents\borland studio projects\console.cpp 72

GetData and GetSize are called on objects that are qualified as const. In such a case the compiler has to assume that both of those functions modify the state of the object, so it disallows the call. You can fix it by qualifying the two member functions as const since they don't actually modify the state:

unsigned GetSize() const
{
	return n;
}

void* GetData() const
{
	return v;
}

Your GetData and GetSize functions need to be declared const
e.g.

unsigned GetSize() const // This
	{
		return n;
	}
void* GetData() const // and this needs to be const
	{					
		return v;
	}

Because the parameter 'a' to the Allocate classes operator = override function has been declared as a constant reference to an Allocate object, then the GetData and SetSize functions have to be declared as const otherwise the compiler thinks that they might attempt to modify the Allocate object....If you follow me!

Cheers for now,
Jas.

edit:
Dammit, beaten to the punch again!

Oops
u proved I'm wrong
thanks

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.