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 14 1986
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()<<end l;
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
On Jun 15, 5:54 pm, "Victor Bazarov" <v.Abaza...@com Acast.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()<<end l;
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
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).
On Jun 15, 6:26 pm, Amol <amolj.1...@gma il.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.
Wolfgang wrote:
On Jun 15, 6:26 pm, Amol <amolj.1...@gma il.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
Wolfgang wrote:
On Jun 15, 5:54 pm, "Victor Bazarov" <v.Abaza...@com Acast.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
On Jun 15, 6:41 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
Wolfgang wrote:
On Jun 15, 6:26 pm, Amol <amolj.1...@gma il.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()<<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().
Wg
Wolfgang wrote:
On Jun 15, 6:41 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
>Wolfgang wrote:
On Jun 15, 6:26 pm, Amol <amolj.1...@gma il.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()<<end l;
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
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.
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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();
}
|
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)
|
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...
|
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...
|
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
| |
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
|
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;
|
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?
|
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',
|
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
|
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look !
Part I. Meaning of...
| |
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...
|
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...
|
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 projectplanning, coding, testing, and deploymentwithout 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...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |