473,387 Members | 1,721 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Const member function

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
14 1950
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
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
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
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
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
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
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
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
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
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
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
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
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

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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Jim West | last post by:
Could someone please explain to me why the code segment class FOO { public: double *begin(); }; void bar(const FOO &foo) { foo.begin(); }
2
by: joe | last post by:
hi, after reading some articles and faq, i want to clarify myself what's correct(conform to standard) and what's not? or what should be correct but it isn't simply because compilers don't...
15
by: Jiří PaleÄek | last post by:
Hello, I know the rules for const handling in C++, but I'd like to ask what is the "right" way to use them, eg. when is it appropriate to make a member function const? This came across this...
7
by: Bala L | last post by:
I have a class with a private array data member 'm_array'. I have written a public function, called 'fileRead', to read values into the array from a file. I just noticed that I have declared this...
2
by: Lionel B | last post by:
I have a function which takes a functor argument. I which to call it for a functor which is actually a class member; this works fine, using the mem_fun_ref and bind1st functions (see listing 1...
4
by: grizggg | last post by:
I have searched and not found an answer to this question. I ran upon the following statement in a *.cpp file in a member function: static const char * const pacz_HTMLContentTypeHeader =...
10
by: subramanian100in | last post by:
The following is a beginner's question. Suppose TYPE1 and TYPE2 are two types for which suitable ctors and operator= are defined. Suppose I have class Test { TYPE1 mem1;
2
by: Angus | last post by:
I have a member function, int GetLogLevel() which I thought I should change to int GetLogLevel() const - I made the change and it works fine. But in the function I am creating buffers and of...
12
by: hweekuan | last post by:
hi, it seems i can't assign the const variable u in class A, one way to solve the problem may be to build a copy constructor. however, why does C++ or vector class not like this code? my g++ is:...
8
by: Ruben | last post by:
error: passing `const Weight' as `this' argument of `float Weight::wgt()' discards qualifiers seems to be some sort of standard error format that I'm not understanding. I have code that...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.