473,738 Members | 1,949 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 #1
17 3272
cheeser wrote:
#include <iostream>

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

int main(int argc, char* argv[]) {
const foo a(42);
a.print();
return 0;
}


Jul 19 '05 #2
"cheeser" <ch**********@y ahoo.com> wrote in message
news:vo******** ****@news.super news.com...

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!
The invoke the function with a const object.

const foo a(42);
// a.print();

// Here's one way to do it. Is there a more elegant way?
Define "elegant".
// Making a const is not within the scope of my question!
You're asking about const member functions, so yes it is,
whether you deny it or not. :-)
static_cast<con st foo>(a).print() ;

return 0;
}


What real specific problem are you trying to solve?

-Mike
Jul 19 '05 #3
> Please see the question in the code below...

Thanks!
Dave
#include <iostream>

using namespace std;
Are you sure you want that?
class foo
{
public:
foo(int d) : data(d) {}
void print() const {cout << "const" << endl;}
This would be called with

const foo f;
f.print();
void print() {cout << "non-const" << endl;}
And that would be called with

foo f;
f.print();
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() ;


Whether a const member function will be called or not depends
on the constness of the object. Why do you want that? Perhaps
we could find another way.
Jonathan
Jul 19 '05 #4
> > 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() ;


Whether a const member function will be called or not depends
on the constness of the object. Why do you want that? Perhaps
we could find another way.


Here's the original code again:

#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;
}
OK, let me take a stab again at articulating what I'm after. There are two
member functions in class foo that I care about: print() and print() const.
If I had a const foo, I would be restricted to calling only print() const.
However, I don't have a const foo (it's the whole point of the problem;
please don't change it to const or you'll be answering a question different
than what I asked, and one that I know the answer too!). Therefore, it is
*semantically* valid for me to call either print() or print() const. This
can be verified by removing the non-const print(). In that case, the
non-const foo object will correctly invoke print() cont.

My question is nothing more than trying to verify that, other than with a
cast to const foo, it is not *syntactically* possible for me to call print()
const (even though it is *semantically* legal, as detailed above). In other
words, I can't do this:

a.print() cost;

Hmmm, it just occurred to me that there may be a way with using a
pointer-to-member, but that would be somewhat ugly too. I think I may have
exhausted the possibilities, but I'm merely throwing this out to those more
experienced than I for confirmation...
Jul 19 '05 #5

"cheeser" <ch**********@y ahoo.com> wrote in message
news:vo******** ****@news.super news.com...
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() ;
Whether a const member function will be called or not depends
on the constness of the object. Why do you want that? Perhaps
we could find another way.


Here's the original code again:

#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;
}
OK, let me take a stab again at articulating what I'm after. There are

two member functions in class foo that I care about: print() and print() const. If I had a const foo, I would be restricted to calling only print() const.
However, I don't have a const foo (it's the whole point of the problem;
please don't change it to const or you'll be answering a question different than what I asked, and one that I know the answer too!). Therefore, it is
*semantically* valid for me to call either print() or print() const. This
can be verified by removing the non-const print(). In that case, the
non-const foo object will correctly invoke print() cont.

My question is nothing more than trying to verify that, other than with a
cast to const foo, it is not *syntactically* possible for me to call print() const (even though it is *semantically* legal, as detailed above). In other words, I can't do this:

a.print() cost;

Hmmm, it just occurred to me that there may be a way with using a
pointer-to-member, but that would be somewhat ugly too. I think I may have exhausted the possibilities, but I'm merely throwing this out to those more experienced than I for confirmation...


Since neither version of your 'print()' function modifies
the object, there isn't really any reason to define a non-const
'print()' function at all.

Just remove the nonconst version, and the const version
will be invoked for const or nonconst objects.

-Mike
Jul 19 '05 #6
> Just remove the nonconst version, and the const version
will be invoked for const or nonconst objects.

-Mike


That is correct, but it evades the whole point of the question! The question
may as well not even be asked if I go with something that doesn't address
the point of what I'm getting at!

I think by now I could probably safely conclude that the answer to my
question is that there's no way to do what I was asking about.

Thanks,
Dave
Jul 19 '05 #7

"cheeser" <ch**********@y ahoo.com> wrote in message
news:vo******** ****@news.super news.com...
Just remove the nonconst version, and the const version
will be invoked for const or nonconst objects.

-Mike
That is correct, but it evades the whole point of the question!


I still fail to see the point.
The question
may as well not even be asked if I go with something that doesn't address
the point of what I'm getting at!
Which is?

Are you asking if you can circumvent the design of C++?
Yes, in many cases you can. Your casting example is how
in this particular case.

I think by now I could probably safely conclude that the answer to my
question is that there's no way to do what I was asking about.


No, not without a cast. I think I have a much better question:
*Why* do you want to do this?

-Mike
Jul 19 '05 #8
> > Whether a const member function will be called or not depends
on the constness of the object. Why do you want that? Perhaps
we could find another way.
Here's the original code again:


<snipped again>
OK, let me take a stab again at articulating what I'm after.


That is not what I asked. Your question has been answered, it
is not possible to call a const member function from a non
const object if it is overloaded with a non-const function,
except with casting (which makes the object const, back to the
starting point).

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.
Jonathan
Jul 19 '05 #9
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
Jul 19 '05 #10

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

Similar topics

9
2255
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
4059
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
3244
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
1591
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
1386
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
6560
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
1847
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
2528
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
940
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
1970
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
8787
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
9473
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
9208
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
8208
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
6750
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
6053
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
4569
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...
2
2744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
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.