473,748 Members | 2,231 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to invoke member function over by "const"?

#include <string>
#include <iostream>
using namespace std;

class TConst
{
private:
string con;
string uncon;
public:
TConst():con("c onst"),uncon("U n const"){}
string GetString()cons t;
string& GetString();
};
//how can I invoke this member function?
string TConst::GetStri ng()const
{
return con;
}
string& TConst::GetStri ng()
{
return uncon;
}

int main()
{
TConst tc;
const string& csr=tc.GetStrin g();
const string cs=tc.GetString ();
string& sr=tc.GetString ();
string s=tc.GetString( );

cout<<"const string& csr="<<csr<<end l;
cout<<"const string cs="<<cs<<endl ;
cout<<"string& sr="<<sr<<endl ;
cout<<"string s="<<s<<endl;
}

===output====== =======
const string& csr=Un const
const string cs=Un const
string& sr=Un const
string s=Un const
===output end=====

why all the call "GetString( )" invoke the un const function.
--
= = = = = = = = = = = = = = = = = = = = = =

       ----------------------------
Co.: beijing lingtu
Ad.: beijing shangdi
ZIP 100094
Tel.: 010-82825800*8006
Mobile:
Mailzh******* ***@lingtu.com
MSN: re********@hotm ail.com
Com. http://www.lingtu.com/
Online:http://www.51ditu.com/
--------------------------
Aug 3 '06 #1
16 2112
recover wrote:
#include <string>
#include <iostream>
using namespace std;

class TConst
{
private:
string con;
string uncon;
public:
TConst():con("c onst"),uncon("U n const"){}
string GetString()cons t;
string& GetString();
};
//how can I invoke this member function?
You need a const object for that.
string TConst::GetStri ng()const
{
return con;
}
string& TConst::GetStri ng()
{
return uncon;
}

int main()
{
TConst tc;
The 'tc' is a NON-const object (in this scope, anyway).
const string& csr=tc.GetStrin g();
const string cs=tc.GetString ();
string& sr=tc.GetString ();
string s=tc.GetString( );

cout<<"const string& csr="<<csr<<end l;
cout<<"const string cs="<<cs<<endl ;
cout<<"string& sr="<<sr<<endl ;
cout<<"string s="<<s<<endl;
}

===output====== =======
const string& csr=Un const
const string cs=Un const
string& sr=Un const
string s=Un const
===output end=====

why all the call "GetString( )" invoke the un const function.
Because all invocations are for the 'tc' object an it is non-const.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 3 '06 #2
recover wrote:
#include <string>
#include <iostream>
using namespace std;

class TConst
{
private:
string con;
string uncon;
public:
TConst():con("c onst"),uncon("U n const"){}
string GetString()cons t;
string& GetString();
};
//how can I invoke this member function?
string TConst::GetStri ng()const
{
return con;
}
string& TConst::GetStri ng()
{
return uncon;
}

int main()
{
TConst tc;
const string& csr=tc.GetStrin g();
const string cs=tc.GetString ();
string& sr=tc.GetString ();
string s=tc.GetString( );

cout<<"const string& csr="<<csr<<end l;
cout<<"const string cs="<<cs<<endl ;
cout<<"string& sr="<<sr<<endl ;
cout<<"string s="<<s<<endl;
}

===output====== =======
const string& csr=Un const
const string cs=Un const
string& sr=Un const
string s=Un const
===output end=====

why all the call "GetString( )" invoke the un const function.
Because the function that is called depends upon the object making the
call (tc) and does not depend upon what you assign the result of the
function call to. If you want to call the const member function then
you need to invoke GetString on a const object.

const TConst tc;
tc.GetString();

Or, you can cast a non-const TConst to a const TConst.
Aug 3 '06 #3
recover posted:
why all the call "GetString( )" invoke the un const function.

class MyClass {
public:

void Func() {}

void Func() const {}
};

int main()
{
MyClass obj;
MyClass const cobj;

obj.Func() /* Non-const version */
cobj.Func() /* Const version */

const_cast<MyCl ass const&>(obj).Fu nc() /* Const version */
/* Or if you have a phobia of "const_cast "
(as many people here seem to have), then
you can use a reference instead: */

MyClass const &cr = obj;

cr.Func(); /* Const Version */
}
I wonder would it be UB to call the non-const function on a const object
(if the non-const function doesn't alter any member data)? Something like:

const_cast<MyCl ass&>(cobj).Fun c();

Anyone know if that's forbidden?

--

Frederick Gotham
Aug 3 '06 #4
Frederick Gotham wrote:
...
I wonder would it be UB to call the non-const function on a const object
(if the non-const function doesn't alter any member data)? Something like:

const_cast<MyCl ass&>(cobj).Fun c();

Anyone know if that's forbidden?
...
No, it is not UB. As long as (as you said) the member function doesn't alter any
member data

--
Best regards,
Andrey Tarasevich
Aug 3 '06 #5
Andrey Tarasevich wrote:
Frederick Gotham wrote:
>...
I wonder would it be UB to call the non-const function on a const
object (if the non-const function doesn't alter any member data)?
Something like:

const_cast<MyCl ass&>(cobj).Fun c();

Anyone know if that's forbidden?
...

No, it is not UB. As long as (as you said) the member function
doesn't alter any member data
Why is the function that doesn't alter any data *not* declared 'const',
that's what I'd be asking...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 3 '06 #6
Victor Bazarov posted:
Why is the function that doesn't alter any data *not* declared 'const',
that's what I'd be asking...

Instead of altering member objects, it could alter resources:

class MyClass {

int *const p;

MyClass() : p(new int[64]) {}

void SetElement(unsi gned const index, int const val) /* Non-const */
{
p[index] = val;
}
};
Depending on the design of the class, it might make perfect sense to make the
above method non-const, even though it doesn't alter any member objects.

--

Frederick Gotham
Aug 3 '06 #7
Frederick Gotham wrote:
Victor Bazarov posted:
>Why is the function that doesn't alter any data *not* declared
'const', that's what I'd be asking...


Instead of altering member objects, it could alter resources:

class MyClass {

int *const p;

MyClass() : p(new int[64]) {}

void SetElement(unsi gned const index, int const val) /* Non-const
*/ {
p[index] = val;
}
};
Depending on the design of the class, it might make perfect sense to
make the above method non-const, even though it doesn't alter any
member objects.
OK. I'll bite.

If such function is non-const, why would somebody try to call it in the
context where the object is const and thus requires a const_cast to call
the non-const member function? If the design of the class is done right,
there would be no circumstances under which a call to 'SetElement' needs
to be done in a function where 'MyClass' object is const, do you agree?

Generally speaking, it's not UB (what you asked about), but makes no
sense in a well-designed program.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 3 '06 #8
Frederick Gotham wrote:
Victor Bazarov posted:
Why is the function that doesn't alter any data *not* declared 'const',
that's what I'd be asking...


Instead of altering member objects, it could alter resources:

class MyClass {

int *const p;

MyClass() : p(new int[64]) {}

void SetElement(unsi gned const index, int const val) /* Non-const */
{
p[index] = val;
}
};
Depending on the design of the class, it might make perfect sense to make the
above method non-const, even though it doesn't alter any member objects.
In the spirit of making as much const as possible, I prefer using
wrappers and containers (e.g., std::vector) that enforce "deep
constness" for their wrapped/contained values and applying mutable
where that behavior is not desirable. Thus, your SetElement() function
wouldn't be declared const, not just because it shouldn't be for
semantic purposes, but because it *couldn't* be.

Cheers! --M

Aug 3 '06 #9
Victor Bazarov posted:
If such function is non-const, why would somebody try to call it in the
context where the object is const and thus requires a const_cast to call
the non-const member function? If the design of the class is done right,
there would be no circumstances under which a call to 'SetElement' needs
to be done in a function where 'MyClass' object is const, do you agree?

Generally speaking, it's not UB (what you asked about), but makes no
sense in a well-designed program.

Yes, I see what your getting at. But there are times when the programmer
has to do some "funky stuff" to achieve something which can't be achieved
via domestic means.

Let's say that there's ONE instance in our program where we want to invoke
this non-const method upon a const object; If we were to be perfectly
politically correct about it, then we would re-engineer our design.

But... then we might think, "Is it warranted to dump our brilliant design
just because we circumvent it in one measly place?".

My answer is "No". It's great for a design to be consistent, and durable,
and all that... but in my opinion, there's nothing wrong with "digging
under the fence" once or twice -- so long as it all comes together
perfectly in the end.

Think back to when you first encountered "const_cast ". I think EVERY
person's first reaction was, "Oh, this has GOT to be dirty; what could it
possibly achieve legitimately?". Over time, we began to see that
"const_cast " really isn't dirty at all -- it just provides us a way of
"digging under the fence".

So, depending on what our program does, and depending on what our class
does, there may be legitimate places throughout the program where we invoke
this non-const method upon a const object... ?

--

Frederick Gotham
Aug 3 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
16960
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(); }
11
4766
by: Der Andere | last post by:
What exactly is the sense of using a "const" modifier before a function declaration? Actually, you can use it in three places. For instance, take a look at the following function declaration (from the introductory book "Absolute C++" by W. Savitch, p. 315) class Money { Money(); const Money operator + (const Money& amount2) const; private:
11
3249
by: snnn | last post by:
On the book <Generic Programming and the STL>( Matthew . H . Austern ),this function is defined as iterator set::begin() const. However, why should a const object returns a non-const iterator? Then, I found, in this book, the semantic of set::iterator is defined as same as set::const_iterator. Both of them must be const! I tried to read the source of GNU STL(version 3.4.1).They were using a red-black tree to implant it (std::set has a...
3
1877
by: Alexander Farber | last post by:
Hi, does anyone have an idea, why do I get the following error (I have to use g++296 on RedHat Linux as compiler): In file included from r_dir.cpp:9: r_obey.h:262: declaration of `const AreaSet &CObeyFile::AreaSet () const' r_areaset.h:197: changes meaning of `AreaSet' from `class AreaSet'
9
3625
by: July | last post by:
Hello! consider the following code: class A { public: virtual void f() const{ cout << "A::f()" << endl; } };
1
1833
by: liguoqiang_0121 | last post by:
Hi,all Please look program. class AA { public: void hello(); }; void AA::hello() { printf("this is class AA\n");
2
2516
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
7
1931
by: Luna Moon | last post by:
Hi all, I just couldn't get myself clear about the usage of "const" in front of and/or behind variables, pointers, classes, objects and functions... It's too confusing... any good clear article/tutorial that can help me? Thanks a lot!
6
2404
by: .rhavin grobert | last post by:
hello;-) i frequently need the following construction: ReturnParam Function() { /...do something.../ someType var = something; /...do something.../ return something;
0
8979
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, 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...
0
8818
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
9522
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...
0
9355
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9225
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
6069
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4589
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...
0
4860
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3296
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 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.