473,761 Members | 6,993 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Picking const vs. non-const member functions upon a call


Hello all,

Please see the question in the code below...

Thanks!
Dave
#include <iostream>

using namespace std;

class foo
{
public:
foo(int d) : data(d) {}
void print() const {cout << "const" << endl;}
void print() {cout << "non-const" << endl;}

private:
int data;
};

int main()
{
foo a(42);

// The call below calls the non-const print();
// I want the const print() to be called!
// a.print();

// Here's one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<con st foo>(a).print() ;

return 0;
}

Jul 19 '05
17 3278
"cheeser" <ch**********@y ahoo.com> wrote in message
news:vo******** ****@news.super news.com
Mike, Jonathan and Robert,

I merely wanted to verify that it is not possible (without
undesirable casts or other things of that ilk) to invoke a const
method from a non-const object if there is also a non-const method of
the same name. I do not have a specific application at hand; I just
wanted confirmation that my understnading that it can't be done is
correct. You have provided that confirmation. For this I offer my
thanks.

A good evening to all,
Dave


Same name yes, if the arguments can differ.

class foo
{
public:
foo(int d) : data(d) {}
void print(int a=0) const {cout << "const" << endl;}
void print() {cout << "non-const" << endl;}
private:
int data;
};
int main()
{
foo a(42);
const foo b(43);

a.print(); // non-const
a.print(0); // const
b.print(); // const
return 0;
}
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)
Jul 19 '05 #11
cheeser wrote:

// The call below calls the non-const print();
// I want the const print() to be called!
// a.print();

// Here's one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<con st foo>(a).print() ;


Here's an alternative, but I don't know if I'd consider it any more elegant:

const foo &ca = a;
ca.print();

I believe that will do what you are asking.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #12
John Carson wrote:
"cheeser" <ch**********@y ahoo.com> wrote in message
news:vo******** ****@news.super news.com
Mike, Jonathan and Robert,

I merely wanted to verify that it is not possible (without
undesirable casts or other things of that ilk) to invoke a const
method from a non-const object if there is also a non-const method of
the same name.


Here are a couple of other suggestions.

class foo
{
public:
foo(int d) : data(d) {}
void print() const {cout << "const" << endl;}
void print() {cout << "non-const" << endl;}
void cprint() const { print(); }
private:
int data;
};
int main()
{
foo a(42);
const foo & b(a);

a.print(); // non-const
b.print(); // const
a.cprint(); // const
return 0;
}

Jul 19 '05 #13

"Kevin Goodsell" <us************ *********@never box.com> wrote in message
news:ie******** ********@newsre ad4.news.pas.ea rthlink.net...
cheeser wrote:

// The call below calls the non-const print();
// I want the const print() to be called!
// a.print();

// Here's one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<con st foo>(a).print() ;

Here's an alternative, but I don't know if I'd consider it any more

elegant:
const foo &ca = a;
ca.print();

I believe that will do what you are asking.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.


Ahh, there it is! I had a feeling there had to be a way, but my mind just
didn't get on the right track... Thanks man...
Jul 19 '05 #14
In article <vo************ @news.supernews .com>, ch**********@ya hoo.com
says...

[ ... ]
// The call below calls the non-const print();
// I want the const print() to be called!
First of all, if you care much about this, it's probably a good clue
that your design has major problems.
// a.print();

// Here's one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<con st foo>(a).print() ;


You have (at least) a few other choices, such as temporarily creating a
reference to a const object, but they all come out the same. If a
member function is overloaded based on const-ness, then the const
overload should only be selected when you invoke it on (a reference or
pointer to) a const object. Therefore, if you want to invoke the const
member function, you need to treat the object as const, either through a
cast (as you've already mentioned) or by referring to the object via a
pointer or reference to const.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 19 '05 #15

"cheeser" <ch**********@y ahoo.com> wrote in message
news:vo******** ****@news.super news.com...

#include <iostream>

using namespace std;

class foo
{
public:
foo(int d) : data(d) {}
void print() const {cout << "const" << endl;}
void print() {cout << "non-const" << endl;}

private:
int data;
};

int main()
{
foo a(42);

// The call below calls the non-const print();
// I want the const print() to be called!
// a.print();

// Here's one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<con st foo>(a).print() ;


I don't know what the "scope" of your question is, but the obvious answer to
me would be to define
const foo a(42);
But if that's not what you want, I think you should question if you really
want a const and non-const version of the same function.
Jul 19 '05 #16

"Jonathan Mcdougall" <jo************ ***@DELyahoo.ca > wrote in message
news:N6******** ************@we ber.videotron.n et...

My question was : why do you want that? Perhaps we could find
another way. Post some real code with your real design with
some real problems.


Why are you guys badgering this guy? He already said there is no point
other than knowing whether or not it can be done.
Jul 19 '05 #17

"Kevin Goodsell" <us************ *********@never box.com> wrote in message
news:ie******** ********@newsre ad4.news.pas.ea rthlink.net...
cheeser wrote:

// The call below calls the non-const print();
// I want the const print() to be called!
// a.print();

// Here's one way to do it. Is there a more elegant way?
// Making a const is not within the scope of my question!
static_cast<con st foo>(a).print() ;

Here's an alternative, but I don't know if I'd consider it any more

elegant:
const foo &ca = a;
ca.print();

I believe that will do what you are asking.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.


In fact, here's the full extent of possibilities:

#include <iostream>

using namespace std;

class foo
{
public:
void bar() {cout << "bar()" << endl;}
void bar() const {cout << "bar() const " << endl;}
void bar() volatile {cout << "bar() volatile" << endl;}
void bar() const volatile {cout << "bar() const volatile" << endl;}
};

int main()
{
foo p;
const foo &c = p;
volatile foo &v = p;
const volatile foo &cv = p;

p.bar();
c.bar();
v.bar();
cv.bar();

return 0;
}
Jul 19 '05 #18

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

Similar topics

9
2257
by: Bart Nessux | last post by:
I am using method 'a' below to pick 25 names from a pool of 225. A co-worker is using method 'b' by running it 25 times and throwing out the winning name (names are associated with numbers) after each run and then re-counting the list and doing it all over again. My boss thinks that 'b' is somehow less fair than 'a', but the only thing I see wrong with it is that it is really inefficient and ugly as it's doing manually what 'a' does...
2
4061
by: Erik Max Francis | last post by:
I was interesting in adding selection and hit testing to ZOE, and was looking at the PyOpenGL wrappers' handling of selection and picking. I see glSelectBuffer to specify the size of the buffer, and glRenderMode properly returns the number of hits when put back into GL_RENDER mode, but I don't see any way within PyOpenGL itself to access the select buffer to actually process the hits. Is there any way to do this without using...
46
3255
by: RoSsIaCrIiLoIA | last post by:
Write a function that gets an array of unsigned int fill it with random values all differents, and sorts it. It should be faster than qsort too. Do you like my solution? _______________________ #include <stdio.h> #include <stdlib.h> #include <time.h>
1
1593
by: Adam Clauss | last post by:
I have a few variables that I want declared as global. To accomplish this, I made the files globals.h and globals.cpp. In globals.h I have the declarations for the structs, and one variable actually defined. It is defined w/ the extern keyword. Then, in globals.cpp I actually define that extern variable. If my understanding of this is correct, then by any file that needs access to this variable simply needs to include globals.h...
5
1389
by: kpp9c | last post by:
I have a several list of songs that i pick from, lets, say that there are 10 songs in each list and there are 2 lists. For a time i pick from my songs, but i only play a few of the songs in that list... now my wife, Jessica Alba, comes home, and i start playing from Jessica's list of songs. After playing a few songs, Jessica, who needs her beauty sleep, goes to bed, and i start my play loop which starts picking from my songs again... ...
8
6562
by: Candace | last post by:
I am using the following code to pick off each digit of a number, from right to left. The number I am working with is 84357. So for the first iteration it should return the number 7 and for the second iteration it should return the number 5, and so on. But for some reason on the first iteration returns the expected results. Each subsequent iteration returns the number plus 1. In order words, when I run the program I am getting: 7, 6, 4, and...
3
1849
by: prassaad | last post by:
HI! I 'm working on linux .I hv difficulty for picking particular line from a file... I like to make some manipulation on LINE such as 3 sda7 333333 66666 888888 444444 from file /PROC/DISKSTATS how I should proceed??? PLZ reply me if u hv answer...... i m waiting.......
2
2533
by: manuboy | last post by:
i am struggling to come up with a c program that is capable of picking up the Y, U and V parameters from a video stream and compare them with that of another stream to calculate the PSNR. i was able to download existing programs from the net but unfortunately that are all part of a library, thus cannot operate on its own. if i have the program below, how do i develop it to compile, for the purpose of calculating PSNR At this stage i...
0
941
by: Jonathan | last post by:
I have 3 webforms on 1 page each with Submit buttons. VB.net code activated by clicking the submit button in form 3 is not picking up the value of a field in form 2. It is just returning Null or "" even though I enter data in the text box. I am referring to the Form 2 field's unique name as follows: Request.Form("UserEmailAddress")
9
1972
by: newbiegalore | last post by:
Hello everyone :-) , Thanks to the gentle people on this group for helping me out with previous issues. :-D This time round I am facing what I perceive as a simple problem, which I have not found a simple solution for (obviously!). The problem: I need to pick up the URL in the address bar of a browser when a link is clicked What I have done: I have used,
0
9554
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
9376
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
9988
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
9811
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
8813
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...
1
7358
isladogs
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...
0
5266
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
3911
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
3
2788
bsmnconsultancy
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...

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.