Archived

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

ArnoAtWork

C++ returned data

Recommended Posts

ArnoAtWork    138
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
petewood    819
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

eg


#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) {}
private:
int value;
};

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

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