i cant understand this compile time error

hello there,
I am defining a class in a program similiar to 'string' class in standard c++ library <string>

here is the code..

#include <iostream>
using namespace std;

class mystring
{
private:
char* string;

public:
// constructor functions
mystring();
mystring(const char []);
mystring(const mystring &);

char* get() { return string; } // getter function
};

mystring::mystring()
{
string=new char[256];
string="\0";
}

mystring::mystring(const char str[])
{
string=new char[256];
strcpy(string, str);
}

mystring::mystring(const mystring &str)
{
string=new char[256];
strcpy(string, str.get()); // there is error on this line
}

int main()
{
mystring s1="red", s2=s1;

return 0;
}

the error says that
'get' : cannot convert 'this' pointer from 'const class mystring' to 'class mystring &'

I cant understand what is going wrong..

regards
ozair
The prototype of get should be const char* get() const so you can call it from const objects ( as you are doing in the copy constructor.
The first const means that the C string returned by get can't be modified externally, the second means that the function itself doesn't modify the object
you said that we need these const's so that we can call this function from const object but if i remove const from the copy construction parameter then it should not give a error..!
You must pass by const references to a copy constructor
can you explain briefly...?

thanks
A copy constructor must copy the contents of an existing object ( without modifying it ) into the new object

The alternatives are:
- passing by value: It will cause an infinite copy loop since the argument to the constructor itself must be copied to get it's value
- passing by reference: It may modify the argument and it can't take rvalues or const objects
- passing by const reference: Will work
Topic archived. No new replies allowed.