473,748 Members | 10,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning reference to member object

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().NonCon stFoo()
How do i get round this problem. I woul think that
GetObj is logically const as
it does not change the object.This is on MSVC++ V8.0

class Obj
{

};

class Test
{
public:
Obj& GetObj() const
{
return m_obj;
}

private:
Obj m_obj;
};
Jun 27 '08 #1
4 1767
On Jun 18, 1:32*pm, tech <naumansulai... @googlemail.com wrote:
* * * * * * * *Hi, I want to return a reference to memberobject
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().NonCon stFoo()
* * * * * * * How do i get round this problem. I woul thinkthat
GetObj is logically const as
* * * * * * * *it does not change the object.This is on MSVC++ V8.0

* * * * * * * *class Obj
* * * * {

* * * * };

* * * * class Test
* * * * {
* * * * public:
* * * * * * * * Obj& GetObj() const
* * * * * * * * {
* * * * * * * * * * * * return m_obj;
* * * * * * * * }

* * * * private:
* * * * * * * * Obj m_obj;
* * * * };
Hi
const member functions is a kind member functions that you can't
change the state of object through them.
GetObj() is const. so you can't change the state of Test object (here
is m_Obj) via it. on the other hand
it returns the reference to data member. so accord to reference
concept it is ready to change. for example
you can call a non-const member function of class Obj:
class Obj {
void Change() { // ... } // non-const
};

Test t;
t.GetObj().Chan ge();
clearly, this is a contradiction. So before any use Test class
compiler complains.
There are two workarounds:
1. If you intend to change the m_Obj, declare GetObj() as an ordinary
member function.
2. If you intend to return a copy of m_Obj, change the return type to
Obj (return the value of m_Obj)

Good luck
Regards,
Saeed Amrollahi
Jun 27 '08 #2
On 18 Cze, 12:32, tech <naumansulai... @googlemail.com wrote:
class Obj {};

class Test
{
public:
You need 2 versions of this method: for const and non-const use of the
returned reference:

const Obj& GetObj() const
{
return m_obj;
}
Obj& GetObj()
{
return m_obj;
}
>
private:
Obj m_obj;
};
Jun 27 '08 #3
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

tech wrote:
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().NonCon stFoo()
How do i get round this problem. I woul think that GetObj is logically const as
it does not change the object.This is on MSVC++ V8.0
Nope, it is _not_ logically const, because Obj is indeed a part of Test.
If you change Obj, you change Test as well.

You either have to return a const Obj&, or you do not declare GetObj to
be const, or you make both versions.

Cheers,
- -Federico
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

iD8DBQFIWPkZBIp u+y7DlLcRAvs/AJ90Q/3R9GNrINy/T5iv1EaDrmDHJgC fTfV7
KHG7S1uL/5mMYJuHuIS32lE=
=cW54
-----END PGP SIGNATURE-----
Jun 27 '08 #4
tech wrote:
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().NonCon stFoo()
How do i get round this problem. I woul think that
GetObj is logically const as
it does not change the object.This is on MSVC++ V8.0

class Obj
{

};

class Test
{
public:
Obj& GetObj() const
{
return m_obj;
}

private:
Obj m_obj;
};
I think you're a bit confused. When you make a member function const,
you're just saying that *this should be treated as const. So in this
case, the instance of Test on which GetObj is called gets treated as
const. In other words, *this is treated as being a const Test&. Given
that, this->m_obj is treated as a const Obj. You can't bind a non-const
reference to a const object, which is why you're getting an error.

As other people have said, you need some combination of:

Obj& GetObj();
const Obj& GetObj() const;

Regards,
Stu
Jun 27 '08 #5

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

Similar topics

9
11916
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is up to which size m would you expect vector<double> returns_by_value() {
12
3291
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???
5
3102
by: Gent | last post by:
I have two questions which are very similar: Is it possible to return an object in C++. Below is part of my code for reference however I am more concerned about the concept. It seems like the function below is returning a pointer to pointers who are GUID. I am trying to write a wrapper to use in my VB code and what I would prefer to do is be able to return an array of GUID. I remember (not sure) that the concept of arrays does not really...
11
1942
by: JKop | last post by:
AnyClass Blah() { AnyClass poo; return poo; } As we all know, in the above, the compiler is entitled to:
11
2224
by: anand | last post by:
I am an STL newbie trying to build a class DUTBus that has a map object. In my member function, I try to return a Map Object, however, it does not seem to work. I am referring to "Bus getBus()" function. I need to do this because in order to "add" device pins (via registerPin() function. In other words, I need to modify the map by inserting new (key,value) pairs into the object. However, when I try to access the bus object by returning...
4
3262
by: Naren | last post by:
Hi , Is it correct to return reference of a member variable. because it can be like we have already deleted the object and still holding the reference of member variable. A *a = new A; int & r = a.get(); // int& A::get() { //returning a member of class A}
17
3235
by: djcredo | last post by:
Hey all, I want to return a pointer to a struct. Here is what I'lm trying to do: struct Position{ int x; int y; }; Position* GraphicTag::getRenderCentre(){
23
2937
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
160
5871
by: DiAvOl | last post by:
Hello everyone, Please take a look at the following code: #include <stdio.h> typedef struct person { char name; int age; } Person;
0
8984
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
8823
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9530
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
9312
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
9238
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
8237
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4593
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...
3
2206
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.