I have the following code:
StringC StringC::operator+(const StringC& other) const
{
strcat(ps,other.ps);
return ps;
};
with the relevant header as follows:
class StringC {
private:
char* ps;
public:
StringC(char const *);
StringC& operator=(const StringC&);
StringC operator+(const StringC& other) const;
void Print();
It is my understanding that the use of const in the operator+ function should stop me being able to change ps and other however I am able to change both of them still.
I have tried the following:
void Class1::Method1() const
{
Variable = Variable + 1;
};
void Class1::Method1(const int v)
{
v = 0;
Variable = v + 1;
};
And this errors as expected, I assume I am missing something in my use of const, but would have expected the first code to error when using strcat?
It is my understanding that the use of
constin theoperator+function should stop me being able to changepsandotherhowever I am able to change both of them still.
And this is correct. You cannot change ps or other.ps, however, that is not what you are doing. What you are doing is changing the contents of what ps points to, which is not const.
So, in operator+ the type of ps is char * const (constant pointer to a char) and not const char * (pointer to a constant char)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With