overloding and const specifier

K

Kiran Shastry

Hi group,

While trying out a piece of C++ code regarding oveloading,i noticed
the following.

class someclass
{
....
int func(int);
float func(int) const;
....
}

is legal. obviously without the const specifier, the compiler will
complain that overloading can not be done. that's fine.

my doubt is,
when does the const member function gets called???

i tried the following code (full) and noticed that all the while, the
first non-const member function was getting called.

******start of test.cpp******

#include <iostream>
using namespace std;

class A
{
private:
int i_data;
float f_data;

public:
A():i_data(0),f_data(0){};
A(int i,float f=0):i_data(i),f_data(f){};
int value(void);
float value(void) const;
};
inline int A::value()
{
cout<<"executing non-const value()\n";
return i_data;
}
inline float A::value() const
{
cout<<"executing const value()\n";
return f_data;
}

int main()
{
A objA(22,7.0);
int i=-1;
float f=-1.0;
i=objA.value();
cout<<"integer value = "<< i <<endl;
f=objA.value();
cout<<"float value = "<< f <<endl;
return 0;
}

******end of test.cpp******
output:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
executing non-const value()
integer value = 22
executing non-const value()
float value = 22
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I'm not sure if its an expected answer.

I understand that return type of a overloaded function does not matter
in resolving the invocations at the compiler level. Please correct me
if i'm wrong.

FYI,i compiled the program on the windows port of gcc version 3.2
(mingw special 20020817-1).

I am fairly new to C++ and i do not know in what real-world scenario
we might require such things. It is only my academic interest in
knowing how to invoke the const member function in the example sighted
above.

Thanks in Advance
-Kiran Shastry
 
K

Kiran

Josephine Schafer said:
When you call it on a const object of the class.

Change it to const A objA(22,7.0);

Oh!..
thank for your immediate attention and this useful insight.
The output now is -
executing const value()
integer value = 7
executing const value()
float value = 7
the typing error in the subject line is regretted.
thanks again
-Kiran Shastry

 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top