Const member function

W

Wolfgang

As I understand, a const member function is used by const object to
ensure that its instance isn't modified throughout its life. Am I
missing something..

#include <iostream>
using namespace std;

class A{

public:

A(char& str, size_t sz){
pch = new char [sz];
strncpy(pch, &str, sz);
}

char* print() const {
*pch = 'M';
return pch;
}
~A(){
delete pch;
}

private:
char* pch;
};

int main(){

const char str[] = "I a constant";

const A* obj = new A(*str, sizeof(str));
cout<<"obj->print() = "<<obj->print()<<endl;

return 0;
}

Wg
 
V

Victor Bazarov

Wolfgang said:
As I understand, a const member function is used by const object to
ensure that its instance isn't modified throughout its life. Am I
missing something..

No, you got it right. The instance of 'A' in your code below is NOT
modified in the 'print' member function. Some memory pointed to by
the member 'pch' is modified, but that memory is not part of the 'A'
object.
#include <iostream>
using namespace std;

class A{

public:

A(char& str, size_t sz){
pch = new char [sz];
strncpy(pch, &str, sz);
}

char* print() const {
*pch = 'M';
return pch;
}
~A(){
delete pch;

Your program has undefined behaviour here. You're supposed to use

delete[]

since you allocate 'pch' using the array form of 'new'.
}

private:
char* pch;
};

int main(){

const char str[] = "I a constant";

const A* obj = new A(*str, sizeof(str));

Does it even compile? Your constructor takes a reference to non-const
char, and you're dereferencing a pointer to const char...
cout<<"obj->print() = "<<obj->print()<<endl;

return 0;
}

Wg

V
 
W

Wolfgang

Wolfgang said:
As I understand, a const member function is used by const object to
ensure that its instance isn't modified throughout its life. Am I
missing something..

No, you got it right. The instance of 'A' in your code below is NOT
modified in the 'print' member function. Some memory pointed to by
the member 'pch' is modified, but that memory is not part of the 'A'
object.


#include <iostream>
using namespace std;
class A{

A(char& str, size_t sz){
pch = new char [sz];
strncpy(pch, &str, sz);
}
char* print() const {
*pch = 'M';
return pch;
}
~A(){
delete pch;

Your program has undefined behaviour here. You're supposed to use

delete[]
If my understanding is correct, delete[] is called when we want to
delete an array of objects - destructor needs to be called for each
object.

Won't be Ok if we use " delete pch " for deleting char array ?
since you allocate 'pch' using the array form of 'new'.
private:
char* pch;
};
int main(){
const char str[] = "I a constant";

Sorry use -
char str[] = "I a constant"; // instead of const char
str[] = "I a constant";
 
A

Amol

Well see carefully what you're doing
char* print() const {
*pch = 'M';
return pch;
}

you are modifying the CONTENTS at the location pointed by pch and not
the pch
for example pch pointing to 1000 location in memory your code is
modifying the contents at 1000 not the value contained in by
'pch'(i.e. 1000).
 
W

Wolfgang

Well see carefully what you're doing
char* print() const {


you are modifying the CONTENTS at the location pointed by pch and not
the pch
for example pch pointing to 1000 location in memory your code is
modifying the contents at 1000 not the value contained in by
'pch'(i.e. 1000).

Infact, why is it that the compiler is permitting change to the
particular text passed in ( text with which the object is
initialized). Aren't we modifying how the object has been
initialized ?

While a const object shouldn't be modified throughout its life time.
 
V

Victor Bazarov

Wolfgang said:
Infact, why is it that the compiler is permitting change to the
particular text passed in ( text with which the object is
initialized).

The text is not part of the constant object.
Aren't we modifying how the object has been
initialized ?

You're modifying something else only sideways related to your object.
It's essentially the same as you would, for example, output something
in the constant function (isn't that what 'print' is for?), like cout.
The memory you're modifying does NOT belong to your object. Your 'A'
object simply has a pointer to it. There can be countless number of
pointers to the same memory and anybody can modify it. Just like
you can access 'cout' in your function and actually modify it (by
outputting to it).
While a const object shouldn't be modified throughout its life time.

Yes. How is that relevant here?

V
 
R

Robert Bauck Hamar

Wolfgang said:
A(char& str, size_t sz){
pch = new char [sz];
strncpy(pch, &str, sz);
}
~A(){
delete pch;

Your program has undefined behaviour here. You're supposed to use

delete[]
If my understanding is correct, delete[] is called when we want to
delete an array of objects - destructor needs to be called for each
object.

Yes, but also the free store management routines need to know what you are
deleting.
Won't be Ok if we use " delete pch " for deleting char array ?

No. Why would Victor tell you that it's wrong if it wasn't?
 
W

Wolfgang

The text is not part of the constant object.


You're modifying something else only sideways related to your object.
It's essentially the same as you would, for example, output something
in the constant function (isn't that what 'print' is for?), like cout.
The memory you're modifying does NOT belong to your object. Your 'A'
object simply has a pointer to it. There can be countless number of
pointers to the same memory and anybody can modify it. Just like
you can access 'cout' in your function and actually modify it (by
outputting to it).


Yes. How is that relevant here?

V

Modifying the code a little bit here, esp changing the data member to
be public - so that I can access outside the class.

#include <iostream>
using namespace std;

class A{

public:

A(char& str, size_t sz){
pch = new char [sz];
strncpy(pch, &str, sz);
}

char* print() const {
*pch = 'M';
return pch;
}
~A(){
delete pch;
}

public:
char* pch;

};

int main(){

char str[] = "I a constant";

const A* obj = new A(*str, sizeof(str));
cout<<"obj->print() = "<<obj->print()<<endl;
cout<<"obj->pch = "<<obj->pch<<endl;
return 0;

}

I'm trying to print the member data which was initialised on the first
place, but modified on calling print().

Wg
 
R

Robert Bauck Hamar

Wolfgang said:
The text is not part of the constant object.


You're modifying something else only sideways related to your object.
It's essentially the same as you would, for example, output something
in the constant function (isn't that what 'print' is for?), like cout.
The memory you're modifying does NOT belong to your object. Your 'A'
object simply has a pointer to it. There can be countless number of
pointers to the same memory and anybody can modify it. Just like
you can access 'cout' in your function and actually modify it (by
outputting to it).


Yes. How is that relevant here?

Modifying the code a little bit here, esp changing the data member to
be public - so that I can access outside the class.

#include <iostream>
using namespace std;

class A{

public:

A(char& str, size_t sz){
pch = new char [sz];
strncpy(pch, &str, sz);
}

More commonly, this should be:

A(char& str, size_t sz) : pch(new char[sz]) {
strncpy(pch, &str, sz);
}

Also: most C++ programmers would expect a C-style string passed as a const
char*, not a char&.
char* print() const {
*pch = 'M';
return pch;
}
~A(){
delete pch;

delete [] pch;
Even though "delete pch" would work on many compilers, it _is_ undefined
behaviour. Don't do it!
}

public:
char* pch;

};

Now, a const A would look like this:
"const class" A {
// member functions
public:
char *const pch;
};

see that pch is const, but it points to non const data.
int main(){

char str[] = "I a constant";

const A* obj = new A(*str, sizeof(str));
cout<<"obj->print() = "<<obj->print()<<endl;
cout<<"obj->pch = "<<obj->pch<<endl;

obj->pch = str // error -- pch is const.
return 0;

}

I'm trying to print the member data which was initialised on the first
place, but modified on calling print().

Yes. This should print "M a constant" in both lines of output. As Victor
says: The text pointed to is not part of *obj as far as C++ is concerned,
only the bits in the pointer itself is. If you want this data to appear as
a member of A, assure A's member functions treat it as such: If print
returned a const char*, and did not modify *pch, then your code would not
be able to modify the data through obj either. (Without performing a
const_cast, that is).
 
V

Victor Bazarov

Wolfgang said:
[..]
Modifying the code a little bit here, esp changing the data member to
be public - so that I can access outside the class.

My comments inline with code relate only to style, not to functionality.
#include <iostream>
using namespace std;

class A{

public:

A(char& str, size_t sz){
pch = new char [sz];
strncpy(pch, &str, sz);
}

A(char const* str, size_t sz) : pch(new char[sz]) {
strncpy(pch, str, sz);
}
char* print() const {
*pch = 'M';
return pch;
}
~A(){
delete pch;
}

public:
char* pch;

};

int main(){

char str[] = "I a constant";

char const str[] = "I a constant";
const A* obj = new A(*str, sizeof(str));

const A* obj = new A(str, sizeof(str));
cout<<"obj->print() = "<<obj->print()<<endl;
cout<<"obj->pch = "<<obj->pch<<endl;
return 0;

}

I'm trying to print the member data which was initialised on the first
place, but modified on calling print().

I think you're missing something conceptual here. The data member
is _a pointer_, not the memory you allocated using 'new[]'. The
member, a pointer, does NOT change. You can print its value by
casting it to (void*). You will see that 'print' does not change
the value of the pointer and therefore does not change the value of
the constant object.

What you are changing is the contents of some memory which the 'pch'
pointer points to. That memory does NOT belong to your 'obj'. NOT.
Do you not understand that? There is no other ownership relationship
between 'obj' and the memory you allocate in 'A::A' than in your mind.

The compiler cannot prevent you from modifying that memory since it
is NOT part of the constant object 'obj'. Only _immediate_ parts of
the constant object cannot be modified, like 'pch' value itself. Try
assigning a different value to 'pch' (not to '*pch'), and you will
see what is meant by contant object.

V
 
J

James Kanze

On Jun 15, 5:54 pm, "Victor Bazarov" <[email protected]> wrote:

[...]
~A(){
delete pch;
Your program has undefined behaviour here. You're supposed to use
delete[]
If my understanding is correct, delete[] is called when we want to
delete an array of objects - destructor needs to be called for each
object.
Won't be Ok if we use " delete pch " for deleting char array ?

It might, it might not. It's undefined behavior; an
implementation might choose to define it (although I don't know
of any which do), or it might happen to work by chance. But
it's forbidden by the language.
 
J

James Kanze

As I understand, a const member function is used by const object to
ensure that its instance isn't modified throughout its life. Am I
missing something..

Others have pointed out the technical aspects: the compiler only
understands what is called "bitwise" const. If you think about
it, how can it be otherwise? How can the compiler know whether
a pointer is part of the implementation of the object, and what
it points to is logically part of the object, or whether it is
there to allow navigation to another object, and of course, the
const-ness of the object which contains the pointer doesn't
affect the const-ness of the other object.

What hasn't been mentionned is the fact that you, as author of
the class, do know which pointers are part of your
implementation, and which ones are just for navigation. In a
very real sense, you define what const means for your object.
If parts of the basic bits are not part of your object's "value"
(as seen by client code), you can cast away const or use mutable
to modify them even in const functions. (The classical example
is a cached value, but I find that reference counters and mutexs
tend to occur more frequently.) And if something "pointed to"
is logically part of you object, you don't modify it from a
const function, even though the compiler allows it. This is
called "logical const", and I think that there is pretty much a
consensus today that this is how const in C++ should be used.
 
W

Wolfgang

Wolfgang said:
[..]
Modifying the code a little bit here, esp changing the data member to
be public - so that I can access outside the class.

My comments inline with code relate only to style, not to functionality.
#include <iostream>
using namespace std;
class A{

A(char& str, size_t sz){
pch = new char [sz];
strncpy(pch, &str, sz);
}

A(char const* str, size_t sz) : pch(new char[sz]) {
strncpy(pch, str, sz);
}






char* print() const {
*pch = 'M';
return pch;
}
~A(){
delete pch;
}
public:
char* pch;

int main(){
char str[] = "I a constant";

char const str[] = "I a constant";


const A* obj = new A(*str, sizeof(str));

const A* obj = new A(str, sizeof(str));
cout<<"obj->print() = "<<obj->print()<<endl;
cout<<"obj->pch = "<<obj->pch<<endl;
return 0;

I'm trying to print the member data which was initialised on the first
place, but modified on calling print().

I think you're missing something conceptual here. The data member
is _a pointer_, not the memory you allocated using 'new[]'. The
member, a pointer, does NOT change. You can print its value by
casting it to (void*). You will see that 'print' does not change
the value of the pointer and therefore does not change the value of
the constant object.

What you are changing is the contents of some memory which the 'pch'
pointer points to. That memory does NOT belong to your 'obj'. NOT.
Do you not understand that? There is no other ownership relationship
between 'obj' and the memory you allocate in 'A::A' than in your mind.

Sorry to ask again, just for better understanding

pch(new char [sz] ) or pch = new char [sz]; inside the above
constructor would allocate memory somewhere but it is not part of the
memory allocated for the object. ie.

Its not part of - " const A* obj = new A(str, sizeof(str)); "

and the member data of the class only has a pointer pointing to that
memory location ??. Am I rt ??
 
V

Victor Bazarov

Wolfgang said:
[..] just for better understanding

pch(new char [sz] ) or pch = new char [sz]; inside the above
constructor would allocate memory somewhere but it is not part of the
memory allocated for the object. ie.

Its not part of - " const A* obj = new A(str, sizeof(str)); "

and the member data of the class only has a pointer pointing to that
memory location ??. Am I rt ??

S, U R rt.

V
 
B

BobR

Victor Bazarov wrote in message...
Wolfgang said:
[..] just for better understanding
pch(new char [sz] ) or pch = new char [sz]; inside the above
constructor would allocate memory somewhere but it is not part of the
memory allocated for the object. ie.

Its not part of - " const A* obj = new A(str, sizeof(str)); "

and the member data of the class only has a pointer pointing to that
memory location ??. Am I rt ??

S, U R rt.

Get off the 'texting' cell-phone and back on your computer. Drink two cups
of coffee. Type this 42 times:
"I will not cave in to kid stuff!"

There, feel better, or do we call Dr. Dobbs again?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,796
Messages
2,569,645
Members
45,372
Latest member
KetozenseACVDiet

Latest Threads

Top