function signatures const vs. non const

A

arun

Hello team,

C++ allows declarations of the fillowing form inside a class, which is
very confusing

void foo();
void foo() const;

My question is when will the second foo() be called as against first
foo()

Similarly

int bar();

const int bar();

Which function will be executed as a result of a call to bar() and
under what circumstances.

Thanks.
 
I

Ian Collins

arun said:
Hello team,

C++ allows declarations of the fillowing form inside a class, which is
very confusing

void foo();
void foo() const;

My question is when will the second foo() be called as against first
foo()
The const form will be called if the object is const, the non-const
otherwise.
 
I

Ian Collins

arun said:
Similarly

int bar();

const int bar();

Which function will be executed as a result of a call to bar() and
under what circumstances.
I forgot this bit, you can't overload a const and non-const return with
the same function signature.
 
R

Rolf Magnus

arun said:
Hello team,

C++ allows declarations of the fillowing form inside a class, which is
very confusing

Only if you don't know what the 'const' means in this place.
void foo();
void foo() const;

My question is when will the second foo() be called as against first
foo()

The second will be called if the object it is called for is const or
accessed through a reference or pointer to const. Otheriwse, the first one
is chosen.
Similarly

int bar();

const int bar();

Which function will be executed as a result of a call to bar() and
under what circumstances.

This shouldn't compile, because the functions have the same signature.
 
B

benben

arun said:
Hello team,

C++ allows declarations of the fillowing form inside a class, which is
very confusing

void foo();
void foo() const;

My question is when will the second foo() be called as against first
foo()

class Circle
{
double radius;
public:
Circle(double r):radius(r){}

double& r(){return radius;}
const double& r() const{return radius;}
};

int main()
{
Circle c1(10);
const Circle c2(20);

// You should be able to read
// a const circle's radius:

double r1 = c1.r(); // calls Circle::r()
double r2 = c2.r(); // calls Circle::r() const

// But not to write to:

c1.r() = 3.5; // OK, writing to a double&
c2.r() = 3.5; // ERROR, cannot write to a const double&
}
Similarly

int bar();

const int bar();

Which function will be executed as a result of a call to bar() and
under what circumstances.

Under no circumstances because this won't compile.

Regards,
Ben
 

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,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top