473,782 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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()<<end l;

return 0;
}

Wg

Jun 15 '07
14 1989
On Jun 15, 3:18 pm, Wolfgang <techreposit... @gmail.comwrote :
On Jun 15, 5:54 pm, "Victor Bazarov" <v.Abaza...@com Acast.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*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
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*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
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...@com Acast.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()<<end l;
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
16963
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
3640
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 support. (first i compiled them with g++3.x. ERR means compiler will bark, otherwise it does accept it. Then the Comeau C/C++ 4.3.3 comes)
15
2143
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 question when I was thinking about implementation of a class implementing some lazy data structure or cache. The C++ rules allow among other possibilities making all member functions non-const, or making all member functions const and all members...
7
1892
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 function to be const. I dont understand how the code compiled and executed without returning an error or a warning. I am assigning values from a file to m_array inside this function. I thought that a member function can be made const only if...
2
2517
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 below). Or, rather, it works fine as long as my member functor is const. The problem comes when I wish to use it for a *non*-const functor (see listing 2 below): *** Start listing 1 *************************************************** // test1.cpp
4
6697
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 = "Content-Type: text/html\r\n"; Why is the second const needed and what does it do? Thanks
10
2189
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
1932
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 course the buffers are filling up with data. So some variable values are changing. So what is rule for a const member function? Is it that only member variables cannot change? But local variables inside the function can?
12
6255
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: gcc version 4.0.1 (Apple Inc. build 5465). thanks for the help. summary of compile error: --------------------------------------- cpp.C:4: error: non-static const member 'const unsigned int A::u',
8
4428
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 looks like this header file
0
9639
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9479
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10311
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8967
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4043
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.