This topic is now archived and is closed to further replies.

C++ returned data

This topic is 5009 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I would like to have two functions with the same name. The difference is that one returns elt and the second returns a const elt. Does the compiler is going to automatically call the good function depending if I will or not modify the elt? Thanks.

Share this post

Link to post
Share on other sites
No, the function doesn't know what the returned value will be used for.

A distinction can be made between two similarly named functions if they are called on const or non-const objects


#include <iostream>

struct A {
void test() const {//can only be called on a const object

std::cout << "const version called\n"
void test() {
std::cout << "non-const version called\n"

struct B {
const int& test() const {//return a const reference

return myInt;
int& test() {
return myInt;
int getValue() const {//have to make const or else can't be called on a cont object - try changing it

return value;
B() : value(0) {}
int value;

int main() {
A object;
const A constObject;

B b;
b.test() = 5;
const B constB;
//constB.test() = 5;//not allowed won't compile

std::cout << b.getValue() << "\n";
std::cout << constB.getValue() << "\n";
return 0;

edit: added constructor to B

[edited by - petewood on March 30, 2004 8:22:01 AM]

Share this post

Link to post
Share on other sites