C++ returned data
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.
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
edit: added constructor to B
[edited by - petewood on March 30, 2004 8:22:01 AM]
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]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement