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

Home Posts Topics Members FAQ

The use of const reference instear of getter

Dear all;

As far as I understand the idea behind getter methods, it is used to
make sure that private memers of a class is returned appropriately to
the calling object.

However, if all I am interested in when making a member private is to
disallow the modification of the value of that member (read-only
member), then how about doing the following:

class A {
public :
const int& ref_to_priv_mem ber;
A() : ref_to_priv_mem ber(priv_member ) {
/* Blah */
}

private :
int private_member;
};

I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?

Looking forwards to hearing your opinions.
Aug 4 '08 #1
26 4423
Turin <om*********@gm ail.comwrites:
Dear all;

As far as I understand the idea behind getter methods, it is used to
make sure that private memers of a class is returned appropriately to
the calling object.

However, if all I am interested in when making a member private is to
disallow the modification of the value of that member (read-only
member), then how about doing the following:
[...]
I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?

Looking forwards to hearing your opinions.
class A {
public :
const int& ref_to_priv_mem ber;
Instead, do this:

inline int ref_to_priv_mem ber(void) const { return private_member; }

this way you have only a right-value, and if the implementation should
change, you won't have to change the client code (only recompile). On
the other hand, inline member functions will be optimized out and
you'll get the same code as with a data member.

--
__Pascal Bourguignon__
Aug 4 '08 #2
On 2008-08-04 13:31, Turin wrote:
Dear all;

As far as I understand the idea behind getter methods, it is used to
make sure that private memers of a class is returned appropriately to
the calling object.

However, if all I am interested in when making a member private is to
disallow the modification of the value of that member (read-only
member), then how about doing the following:

class A {
public :
const int& ref_to_priv_mem ber;
A() : ref_to_priv_mem ber(priv_member ) {
/* Blah */
}

private :
int private_member;
};

I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?
Any good compiler will probably reduce a getter function to the same
thing, with the exception that you can, if you want, easily make changes
to the getter function (such as changing the returned value is certain
cases).

--
Erik Wikström
Aug 4 '08 #3
On 2008-08-04 13:42, Pascal J. Bourguignon wrote:
Turin <om*********@gm ail.comwrites:
>Dear all;

As far as I understand the idea behind getter methods, it is used to
make sure that private memers of a class is returned appropriately to
the calling object.

However, if all I am interested in when making a member private is to
disallow the modification of the value of that member (read-only
member), then how about doing the following:
[...]
I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?

Looking forwards to hearing your opinions.
>class A {
public :
const int& ref_to_priv_mem ber;

Instead, do this:

inline int ref_to_priv_mem ber(void) const { return private_member; }
Nitpick:
inline is superfluous since the function is defined in the class
definition, and in C++ we usually write foo() and not foo(void), the
latter is considered bad style.

--
Erik Wikström
Aug 4 '08 #4
On Aug 4, 7:31*am, Turin <omar.ham...@gm ail.comwrote:
Dear all;

As far as I understand the idea behind getter methods, it is used to
make sure that private memers of a class is returned appropriately to
the calling object.

However, if all I am interested in when making a member private is to
disallow the modification of the value of that member (read-only
member), then how about doing the following:

class A {
* public :
* * const int& ref_to_priv_mem ber;
* * A() : ref_to_priv_mem ber(priv_member ) {
* * * /* Blah */
* * }

* private :
* * int private_member;

};

I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?

Looking forwards to hearing your opinions.
I use the same rule of thumb in this case as I do to determine whether
I should pass an object by const reference to a function - built in
types get passed by value, all others get passed by const reference.

And, BTW, std::string is not a built in type ;).

HTH
Aug 4 '08 #5
In article <7210b453-7a0e-4af3-a159-98f7848d28dd@
34g2000hsh.goog legroups.com>, om*********@gma il.com says...

[ ... ]
However, if all I am interested in when making a member private is to
disallow the modification of the value of that member (read-only
member), then how about doing the following:

class A {
public :
const int& ref_to_priv_mem ber;
A() : ref_to_priv_mem ber(priv_member ) {
/* Blah */
}

private :
int private_member;
};

I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?

Looking forwards to hearing your opinions.

This works perfectly well, and doesn't really have any side-effects.

Contrary to the claims elsethread, there's also no real problem in the
(IME unlikely) event that you need to change what's returned -- instead
of using an (explicit) member function, you can create a small proxy
class something like this:

class A {

struct ref_to_priv_mem ber {
friend class A;
operator const int &() { return private_member; }
private:
int private_member;

};
};

Now, if you need to modify what ref_to_priv_mem ber returns, you can do
it in your operator, without any effect on external code.

This does have a couple of _minor_ side effects. First of all, since
only one user-defined operator will be considered in an implicit
conversion sequence, if you were depending on (for example) returning a
reference to constant int, and having that used to construct some other
object (implicitly) this would break the code. IMO, this is a positive
far more often than a negative -- on the rare occasion that such a
conversion is needed, you're probably better off making it explicit,
such as adding a conversion to the inner class that directly creates the
type you want (or adding a ctor to that type that constructs it directly
from this inner class). At the same time, this prevents such implicit
conversions from happening by accident, making the code substantially
safer.

Second, (and usually more importantly) this keeps you from having ugly
code everywhere on the off chance that some day it'll become useful to
have a member function to produce the desired value instead of allowing
"reading a value" to look like reading a value.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Aug 4 '08 #6
Erik Wikström <Er***********@ telia.comwrites :
On 2008-08-04 13:42, Pascal J. Bourguignon wrote:
>Turin <om*********@gm ail.comwrites:
>>Dear all;

As far as I understand the idea behind getter methods, it is used to
make sure that private memers of a class is returned appropriately to
the calling object.

However, if all I am interested in when making a member private is to
disallow the modification of the value of that member (read-only
member), then how about doing the following:
[...]
I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?

Looking forwards to hearing your opinions.
>>class A {
public :
const int& ref_to_priv_mem ber;

Instead, do this:

inline int ref_to_priv_mem ber(void) const { return private_member; }

Nitpick:
inline is superfluous since the function is defined in the class
definition, and in C++ we usually write foo() and not foo(void), the
latter is considered bad style.
Why?

Is it because it reminds of the C ancestry?

Since I learned C first, I'm always afraid that with foo() it would
accept any number of arguments...

--
__Pascal Bourguignon__
Aug 4 '08 #7
On 2008-08-04 15:54, Pascal J. Bourguignon wrote:
Erik Wikström <Er***********@ telia.comwrites :
>On 2008-08-04 13:42, Pascal J. Bourguignon wrote:
>>Turin <om*********@gm ail.comwrites:

Dear all;

As far as I understand the idea behind getter methods, it is used to
make sure that private memers of a class is returned appropriately to
the calling object.

However, if all I am interested in when making a member private is to
disallow the modification of the value of that member (read-only
member), then how about doing the following:
[...]
I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?

Looking forwards to hearing your opinions.

class A {
public :
const int& ref_to_priv_mem ber;

Instead, do this:

inline int ref_to_priv_mem ber(void) const { return private_member; }

Nitpick:
inline is superfluous since the function is defined in the class
definition, and in C++ we usually write foo() and not foo(void), the
latter is considered bad style.

Why?

Is it because it reminds of the C ancestry?

Since I learned C first, I'm always afraid that with foo() it would
accept any number of arguments...
Well, for one it is inconsistent. If I write foo(bar) it means that foo
takes one argument of type bar, regardless if bar = void or not (in
other words foo(void) means foo takes one argument of type void). So for
me that means that the only way to call foo would be to somehow supply
an argument of type void.

--
Erik Wikström
Aug 4 '08 #8
On Aug 4, 3:52 pm, Jerry Coffin <jcof...@taeus. comwrote:
In article <7210b453-7a0e-4af3-a159-98f7848d28dd@
34g2000hsh.goog legroups.com>, omar.ham...@gma il.com says...
[ ... ]
However, if all I am interested in when making a member
private is to disallow the modification of the value of that
member (read-only member), then how about doing the
following:
class A {
public :
const int& ref_to_priv_mem ber;
A() : ref_to_priv_mem ber(priv_member ) {
/* Blah */
}
private :
int private_member;
};
I would like to know the opinion of C++ experts on this and
if there are any side-effects of this. Also from the
perferformance point of view, isn't using this more effecient
than using a getter?
Looking forwards to hearing your opinions.
This works perfectly well, and doesn't really have any
side-effects.
With most compilers, it will increase the size of the object.
(And since the original poster mentionned performance, I expect
that with most compilers, compared to a getter, it will generate
slower code. Internally, the reference will be implemented as a
pointer, and that ain't good for optimization.)

The other problem is consistency. When you need to return
something that isn't really a member variable, you use a
function call; for the member variable, you use a reference.
Isn't that exposing internal details which the client code
should not be concerned with?

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Aug 4 '08 #9
Turin wrote:
I would like to know the opinion of C++ experts on this and if there
are any side-effects of this.
Also from the perferformance point of view, isn't using this mor
effecient than using a getter?
You have got it completely backwards: Using such a member reference is
going to increase the size of the objects instantiated from the class
(which a member function won't do), it will make instantiating your
class slower (because the reference needs to be initialized) and
accessing the element will be slower (because the compiler will most
probably be unable to optimize the indirection away, as it has no way of
knowing at compile time where the reference is pointing to).

An inline member function will not increment the size of the class,
will have zero overhead at instantiation (and basically anything else),
and will have zero overhead to access the member variable (at least if
the compiler is optimizing).

If what you fear is that a member function will cause slow code,
inlining such a simple member function is one of the easiest
optimizations for any C++ compiler to do. (The only situation where it
will not inline it is when you have all optimizations turned off, eg.
for debugging purposes.)

From an object-oriented point of view your reference is also exposing
the internal implementation details of your class, which the getter
function isn't. (In other words, you could later change the
implementation of your getter function to something completely different
without breaking anything, but you won't be able to do that with your
reference solution.)
Aug 4 '08 #10

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

Similar topics

5
1391
by: gouki | last post by:
class X { // members public: int foo() const; } int X::foo() const // what is the const for??? {
3
5879
by: Shreyas Ranade | last post by:
I want to pass an Object Reference to a C# function, but also I want to make sure that the calling function should not change it's value. The C++ Code Like MyClass cls; Fun1(cls) void Fun1(const MyClass & cls) { int a = cls.m_No;
7
2244
by: th-ko | last post by:
Hi, I would like to know whether a certain coding pattern exist to handle the following problem. I am using a const methode to get and value a from the class. In case the value was not calculated yet, I want to start the calculation (which is not a const methode) and return the value. But since the calculation is not const, I can't call it within the getter. Any ideas? Thanks in advance, Thomas Kowalski
4
1259
by: wenmang | last post by:
Hi, I like to use a const pointer to a shm inside a class, and I don't want to instantiate it through class ctor, is there any other way around? The main purpose for const pointer is to avoid somebody accidently re-assign the pointer to something else in realtime.
4
6694
by: grizggg | last post by:
I have searched and not found an answer to this question. I ran upon the following statement in a *.cpp file in a member function: static const char * const pacz_HTMLContentTypeHeader = "Content-Type: text/html\r\n"; Why is the second const needed and what does it do? Thanks
4
2890
by: Noah Roberts | last post by:
I am trying to keep a vector of tuples sorted based on the first member and so for my insert function I am calling std::lower_bound with a bound comparator like the following: std::lower_bound(sit, eit, t, boost::bind(tuple_t::get<0>(), _1) < boost::bind(tuple_t::get<0>(), _2)); The problem is that get<is overloaded via const. There are the two definitions:
8
4427
by: Ruben | last post by:
error: passing `const Weight' as `this' argument of `float Weight::wgt()' discards qualifiers seems to be some sort of standard error format that I'm not understanding. I have code that looks like this header file
6
2404
by: .rhavin grobert | last post by:
hello;-) i frequently need the following construction: ReturnParam § Function() § { /...do something.../ someType var § = something; /...do something.../ return something;
1
2825
by: rottmanj | last post by:
I have written a class that manages all the database connection information/methods I need to connect to a database and query off of it. In order to make my application dynamic so that it can read from multiple tables I setup 4 variables that I will populate at another time. These variables hold the data for database I want to connect to. Currently when I run the code, I end up with this as the output. test �y������� DB connection...
0
9541
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...
0
9370
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9321
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
9247
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
8242
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
6796
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
6074
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
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2215
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.