473,698 Members | 2,873 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning const reference value from functions


Hello All,
When will it be benefical to return a value from a function as a const reference
?

Say I have classes like this

class B {
public:
int someValue1;
int someValue2;
void ChangeValue();
void ConstFunc() const;
};

void B::ChangeValue( )
{
int tmp = someValue1;
someValue1 = someValue2;
someValue2 = tmp;
}
class A {
public :
int value;
void inspect(const B& b);
const B& returnConstRef( );
private :
int someInt;
B classB;
};

const B& A::returnConstR ef()
{
return classB;
}

In the above class, returnConstRef returns a const reference to B. So whatever
we get like this should not be able to change class B like below. Also the
compiler should not allow me to assign a non-const class B (classB) to classA.
returnConstRef( ).

A classA;
B classB = classA.returnCo nstRef();
classB.ChangeVa lue();

With the above code there is no problem with the compiler. I am wrong some where
in my understanding of the returning values by reference, Can somebody please
correct ?

Thanks in advance
KInd.
--
Use our news server 'news.foorum.co m' from anywhere.
More details at: http://nnrpinfo.go.foorum.com/
Jul 22 '05 #1
3 2137
Sree wrote:

Hello All,
When will it be benefical to return a value from a function as a const reference
?
When the cost of returning by value is to high due to copying of the
return value.
With builtin types like int, double, char, ... this is practically never
the case. User defined types need to have a closer inspection.

[snip]
Also the
compiler should not allow me to assign a non-const class B (classB) to classA.
returnConstRef( ).
Maybe I read something different to what you intended. But: Why should
the compiler not allow this?

A classA;
B classB = classA.returnCo nstRef();
classB.ChangeVa lue();


That does something completely different.
A new B object is constructed, which is initialized from the
B object in A.
After that classB and the B object in classA have nothing in common.
This would not change, if you didn't return a const reference, but
a non const instead.
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #2
In message <20************ *******@foorum. com>, Sree
<no************ @f-m.fm> writes

Hello All,
When will it be benefical to return a value from a function as a const
reference
?
See the thread "Read-only, as opposed to const member" for a lot more
debate on this issue ;-)

Say I have classes like this

class B {
public:
int someValue1;
int someValue2;
void ChangeValue();
void ConstFunc() const;
};

void B::ChangeValue( )
{
int tmp = someValue1;
someValue1 = someValue2;
someValue2 = tmp;
}
class A {
public :
int value;
void inspect(const B& b);
const B& returnConstRef( );
private :
int someInt;
B classB;
};

const B& A::returnConstR ef()
{
return classB;
}

In the above class, returnConstRef returns a const reference to B. So whatever
we get like this should not be able to change class B like below. Also the
compiler should not allow me to assign a non-const class B (classB) to classA.
returnConstRef ().

A classA;
B classB = classA.returnCo nstRef();
This constructs a new B which is a *copy* of the reference returned by
returnConstRef( ). The new B object has no connection with the one in
classA.
classB.ChangeVa lue();
And this can therefore modify the new copy.

Did you perhaps mean to write

B const & classB = classA.returnCo nstRef();
// now classB is a (const) reference to classA.classB
classB.ChangeVa lue(); // this won't compile
?
With the above code there is no problem with the compiler. I am wrong
some where
in my understanding of the returning values by reference, Can somebody please
correct ?


--
Richard Herring
Jul 22 '05 #3
Sree posted:
In the above class, returnConstRef returns a const reference to B. So
whatever we get like this should not be able to change class B like
below.


Wouldn't it be nice if you could make the B object read-only.

class A
{
read-only B objectB;
};
I've written another thread about this entitled "Read only, as opposed to
const member variable". Don't look at my original post, but my second one in
the thread. Essentially it does this:

int main(void)
{
A a;

TakesB(a.object B);

a.objectB = 4; //Compile ERROR

//Essentially, it is read-only
}
-JKop
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
2136
by: cppaddict | last post by:
Hi, Is it considered bad form to have the subscript operator return a const reference variable? If not, what is the proper way to do it? My question was prompted by the code below, my problematic attempt to implement a subscript operator that returns a const reference. The dubious code is marked at the end. <code>
19
1972
by: JKop | last post by:
When I compile and run the following on my system: #include <iostream> static int hello = 78; int ReturnValue(void) {
12
3283
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global function { MFVec res = z1; res += z2 return res; // WHY???
4
1813
by: Siemel Naran | last post by:
Hi. I have found one advantage of returning values through the argument list. It's that we have to store the return value. But when we return by value, we may forgot to store the return value. Consider, void f(int x, int& i); int i, j; f(1, i);
25
2928
by: Victor Bazarov | last post by:
In the project I'm maintaining I've seen two distinct techniques used for returning an object from a function. One is AType function(AType const& arg) { AType retval(arg); // or default construction and then.. // some other processing and/or changing 'retval' return retval; }
13
4509
by: Matthias Kaeppler | last post by:
Hi, I was wondering why library implementors often make getter functions return strings by value (copies). For example, in boost::filesystem the leaf() function returns an std::string by value. So does Gnome::Vfs::FileInfo::get_name(). Isn't that unnecessary overhead? I could as well return by reference to const-string and avoid
10
10287
by: Fraser Ross | last post by:
I need to know the syntax for writing a reference of an array. I haven't seen it done often. I have a class with a member array and I want a member function to return an reference to it. Returning a pointer to the first element might do but I want to do what I've said. Fraser.
23
2934
by: pauldepstein | last post by:
Below is posted from a link for Stanford students in computer science. QUOTE BEGINS HERE Because of the risk of misuse, some experts recommend never returning a reference from a function or method. QUOTE ENDS HERE I have never heard anyone else say that it is a problem for a function
4
1762
by: tech | last post by:
Hi, I want to return a reference to member object provided in class Test, so have provided a getter function GetObj() and declared it const. However i'm getting a compiler error that i need to return reference to const obj but if i do do this i can't call non const member functions eg GetObj().NonConstFoo() How do i get round this problem. I woul think that GetObj is logically const as
0
8683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8904
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8876
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5867
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.