By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,952 Members | 985 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,952 IT Pros & Developers. It's quick & easy.

Const member function

P: n/a
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

Jun 15 '07 #1
Share this Question
Share on Google+
14 Replies


P: n/a
Wolfgang wrote:
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 15 '07 #2

P: n/a
On Jun 15, 5:54 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Wolfgang wrote:
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[]
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";
>
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 15 '07 #3

P: n/a
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).

Jun 15 '07 #4

P: n/a
On Jun 15, 6:26 pm, Amol <amolj.1...@gmail.comwrote:
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).
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.
Jun 15 '07 #5

P: n/a
Wolfgang wrote:
On Jun 15, 6:26 pm, Amol <amolj.1...@gmail.comwrote:
>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).

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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 15 '07 #6

P: n/a
Wolfgang wrote:
On Jun 15, 5:54 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
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?

--
rbh
Jun 15 '07 #7

P: n/a
On Jun 15, 6:41 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Wolfgang wrote:
On Jun 15, 6:26 pm, Amol <amolj.1...@gmail.comwrote:
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).
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
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

Jun 15 '07 #8

P: n/a
Wolfgang wrote:
On Jun 15, 6:41 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
>Wolfgang wrote:
On Jun 15, 6:26 pm, Amol <amolj.1...@gmail.comwrote:
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).
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?

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).

--
rbh
Jun 15 '07 #9

P: n/a
Wolfgang wrote:
[..]
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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 15 '07 #10

P: n/a
On Jun 15, 3:18 pm, Wolfgang <techreposit...@gmail.comwrote:
On Jun 15, 5:54 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
[...]
~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.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 16 '07 #11

P: n/a
On Jun 15, 2:44 pm, Wolfgang <techreposit...@gmail.comwrote:
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.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 16 '07 #12

P: n/a
On Jun 15, 7:52 pm, "Victor Bazarov" <v.Abaza...@comAcast.netwrote:
Wolfgang wrote:
[..]
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.
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 ??

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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask- Hide quoted text -

- Show quoted text -

Jun 16 '07 #13

P: n/a
Wolfgang wrote:
[..] 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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 16 '07 #14

P: n/a

Victor Bazarov wrote in message...
Wolfgang wrote:
[..] 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?

--
Bob <GR
POVrookie
Jun 16 '07 #15

This discussion thread is closed

Replies have been disabled for this discussion.