Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const still allowing changes under operator function c++

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?

like image 818
stuart194 Avatar asked Dec 15 '25 01:12

stuart194


1 Answers

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.

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)

like image 127
NathanOliver Avatar answered Dec 16 '25 17:12

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!