Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ const member function

I am reading a book called 'Effective C++, Second Edition' and its talking about const member functions and how you have bitwise const-ness and conceptual const-ness.

It says most compilers will go with bitwise const-ness, which is that you cannot alter data members of an object inside a const member function.

Then there's an example of a member function that doesn't seem to act bitwise in the const test.

It goes like this:

#include "stdafx.h"
#include <string>
#include <iostream.h>

using namespace std;

class mystring
{

public:
    mystring(const char* value);

    operator char *() const { return data; }

private:
    char * data;
};

mystring::mystring(const char * value)
{

    mystring::data = const_cast<char*>(value);
}


int main(int argc, char* argv[])
{
    const mystring s = "Hello";

    char * nasty = s;

    *nasty = 'M';

    printf("s: %c", s);

    return 0;
}

When this is run, it says in my book it should allow you to change the value of s, even though its const. This because char* data is pointing to the same as const char* value is pointing. *data in this case is not const.

However trying to run this in MS VC++ 6.0, it throws an access violation at line *nasty = 'M';

Can someone explain what is going on? I think I've missed something?

To me it seems that because we have a const mystring s, we should not be able to change it, but then what it says in the books seems awkward.

like image 996
Tony The Lion Avatar asked Apr 15 '26 21:04

Tony The Lion


2 Answers

The access violation is because you try to change a string literal. Your code is equivalent to:

char * p = "Hello";
* p = 'M';

which is illegal in both C and C++ - nothing to do with const member functions.

You get access violation only because the char* pointer is to a string literal. Changing a string literal is undefined behavior (AV in your case), it has nothing to do with const-correctness.

like image 26
sharptooth Avatar answered Apr 17 '26 10:04

sharptooth



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!