473,701 Members | 2,979 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read-only, as opposed to const member

Back when I read my first C++ book, I was given the following scenario:

class Cheese
{
public:

int number_of_holes ;

int colour;

};
The thing is, you want the "user" of this class to be able to read from the
two above variables, but no be able to change them. The book retardly gave
the following:

class Cheese
{
private:

int number_of_holes ;

int colour;

public:

int GetNumberOfHole s(void);

int GetColour(void) ;
};

What do yous think of the following:
class Cheese
{
private:

int number_of_holes ;

int colour;

public:

const int& GetNumberOfHole s(void)
{
return number_of_holes ;
}

const int& GetColour(void)
{
return colour;
}

};

int main(void)
{
Cheese chalk;

chalk.GetNumber OfHoles();
}
I wonder was so many books think they have to show you the stupid way before
they give you the lean, mean, efficient way.
-JKop
Jul 22 '05 #1
39 3082


An even better idea!:
class Cheese
{
private:

int prv_number_of_h oles;

int prv_colour;

public:

const int& number_of_holes ;

const int& colour;

Cheese(void) : number_of_holes (prv_number_of_ holes),
colour(prv_colo ur)
{
;
}

void Blah(void)
{
prv_number_of_h oles = 52;

prv_colour = 2;
}

};
int main(void)
{
Cheese chalk;

TakesInt(chalk. number_of_holes );

chalk.number_of _holes = 52; //Compile error
}
This way, the actual class member functions and also friend functions have
write-access to these member variables, while the "user" only has read-only
access!
-JKop
Jul 22 '05 #2
In message <z%************ *****@news.indi go.ie>, JKop <NU**@NULL.NULL >
writes
Back when I read my first C++ book, I was given the following scenario:

class Cheese
{
public:

int number_of_holes ;

int colour;

};
The thing is, you want the "user" of this class to be able to read from the
two above variables, but no be able to change them. The book retardly gave
the following:

class Cheese
{
private:

int number_of_holes ;

int colour;

public:

int GetNumberOfHole s(void);

int GetColour(void) ;
Both of those should be const functions, and the "void" is unidiomatic.};

What do yous think of the following:
class Cheese
{
private:

int number_of_holes ;

int colour;

public:

const int& GetNumberOfHole s(void)
{
return number_of_holes ;
}

const int& GetColour(void)
{
return colour;
}
I think those should be const functions, too, and you don't need the
"void".
};

int main(void)
{
Cheese chalk;

chalk.GetNumber OfHoles();
Pointless. Didn't you mean

something = chalk.GetNumber OfHoles();

? There's an important difference.}
I wonder was so many books think they have to show you the stupid way before
they give you the lean, mean, efficient way.


Because it's the safe way? Once you start returning references, the
next thing is to try returning references to temporaries, with hilarious
consequences.

What do you think you would gain by returning a reference?

I doubt that returning an int by value is likely to be any more obese or
less efficient than returning a const reference. Even if you'd
substituted some class with a costly copy constructor, don't forget that
ultimately you want to _do_ something with the value of whatever the
function returns, or why call it in the first place? And that means
that somewhere or other there's likely to be a copy operation anyway,
whether you return a value or a reference. Given the existence of return
value optimisation, the difference in cost may be less than you
expected.

--
Richard Herring
Jul 22 '05 #3
JKop wrote:

What do yous think of the following:

class Cheese
{
private:

int number_of_holes ;

int colour;

public:

const int& GetNumberOfHole s(void)
{
return number_of_holes ;
}

const int& GetColour(void)
{
return colour;
}

};

int main(void)
{
Cheese chalk;

chalk.GetNumber OfHoles();
}

I wonder was so many books think they have to show you the stupid way before
they give you the lean, mean, efficient way.


On most typical machines this is no more efficient then returning
the values directly. There is literally no point in replacing
a pass by value with a pass per reference for builtin types
like int, double, char, etc...
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #4
JKop wrote:

An even better idea!:
class Cheese
{
private:

int prv_number_of_h oles;

int prv_colour;

public:

const int& number_of_holes ;

const int& colour;

Cheese(void) : number_of_holes (prv_number_of_ holes),
colour(prv_colo ur)
{
;
}

void Blah(void)
{
prv_number_of_h oles = 52;

prv_colour = 2;
}

};
int main(void)
{
Cheese chalk;

TakesInt(chalk. number_of_holes );

chalk.number_of _holes = 52; //Compile error
}

This way, the actual class member functions and also friend functions have
write-access to these member variables, while the "user" only has read-only
access!


and when the internals of that class Cheese change, all the code that uses
that class breaks immediatly. Congratulations : you just found a clever way
of breaking the concept of encapsulation :-)

Trust your compilers optimizer!
He may do more then you expect.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #5
JKop wrote:
Back when I read my first C++ book, I was given the following scenario:

class Cheese
{
public:

int number_of_holes ;

int colour;

};
The thing is, you want the "user" of this class to be able to read from the
two above variables, but no be able to change them. The book retardly gave
the following:

class Cheese
{
private:

int number_of_holes ;

int colour;

public:

int GetNumberOfHole s(void);

int GetColour(void) ;
};

What do yous think of the following:
class Cheese
{
private:

int number_of_holes ;

int colour;

public:

const int& GetNumberOfHole s(void)
{
return number_of_holes ;
}

const int& GetColour(void)
{
return colour;
}

};

int main(void)
{
Cheese chalk;

chalk.GetNumber OfHoles();
}

I wonder was so many books think they have to show you the stupid way before
they give you the lean, mean, efficient way.


If those funtions are inlined and if you use an optimizing compiler it
will most likely not make a difference whether you return by reference
or return by value. In trivial cases like this example the contents of
the main() function would most likely be completely optimized away
(since everything is inline in this example the compiler can determine
that there are no observable side effects). In cases where the main()
function uses the return values (so the calls to the chalk object can
not be optimized away), the compiler will most likely generate exactly
the same code for both cases.

Note that the optimization story changes when the member functions of
the Cheese class are not inlined (i.e. when the implementation of these
member functions are in a different translation unit). In this case the
compiler does not know what happens inside the member functions, and
therefore the optimizer must be conservative and must call the functions.

For simple types (like int), that have zero construction and destruction
overhead and have very low copy overhead (about the same as copying
pointers which typically happens when dealing with references), there is
most likely no performance gain by using references. In fact in some
cases returning by reference instead of returning by value can even be
slower (taking a peek at assembly code generated by the compiler can be
very instructive). Of course if you have objects that are costly to
copy(construct) using references can give significant performance
benefits, and should be used whenever appropriate.

The reason why books start with the return by value example probably for
educational reasons; start simple first and discuss the more advanced
topics later. Also note that performance is only one of the lofty goals
to pursue. The net effect of the micro optimizations you are after is
usually quite small or even immeasurable. In my experience you are lucky
if you can improve performance that way by more than 20% (there are
exceptions but those are rare). On the other hand it is not rare for
high-level optimizations (e.g. better algorithms) to improve performance
by more than an order of magnitude. You have to consider carefully on
what you spend time. That being said there is obviously no point in
writing needlessly inefficient code.

--
Peter van Merkerk
peter.van.merke rk(at)dse.nl
Jul 22 '05 #6
On Thu, 24 Jun 2004 10:26:39 GMT, JKop <NU**@NULL.NULL > wrote:
Back when I read my first C++ book, I was given the following scenario:

class Cheese
{
public:

int number_of_holes ;

int colour;

};
The thing is, you want the "user" of this class to be able to read from the
two above variables, but no be able to change them. The book retardly gave
the following:

class Cheese
{
private:

int number_of_holes ;

int colour;

public:

int GetNumberOfHole s(void);

int GetColour(void) ;
};
Yes, they miss the const qualification on the member functions, which
is a bad idea.
What do yous think of the following:
class Cheese
{
private:

int number_of_holes ;

int colour;

public:

const int& GetNumberOfHole s(void)
{
return number_of_holes ;
}

const int& GetColour(void)
{
return colour;
}

};
It also misses the const qualification. What's more, the return by
reference exposes the implementation of Cheese, since the class needs
int member variables to return references to. What if you decide to
store the colour as a class internally? You don't want to have to
change the interface.

In addition, returning built-ins by reference is usually a
pessimization - it is slower than return by value, at least until the
optimizer turns it back into return by value!
int main(void)
{
Cheese chalk;

chalk.GetNumber OfHoles();
}
I wonder was so many books think they have to show you the stupid way before
they give you the lean, mean, efficient way.


Neither way is good, but yours is actually more stupid.

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #7
Peter van Merkerk posted:
You have to consider carefully on what you spend time. That being said
there is obviously no point in writing needlessly inefficient code.

I have all the time in the world! Ahh... the joys of unemployment.
-JKop
Jul 22 '05 #8
Richard Herring posted:
In message <z%************ *****@news.indi go.ie>, JKop <NU**@NULL.NULL >
writes
Back when I read my first C++ book, I was given the following scenario:

class Cheese
{
public:

int number_of_holes ;

int colour;

};
The thing is, you want the "user" of this class to be able to read from
the two above variables, but no be able to change them. The book
retardly gave the following:

class Cheese
{
private:

int number_of_holes ;

int colour;

public:

int GetNumberOfHole s(void);

int GetColour(void) ;
Both of those should be const functions, and the "void" is unidiomatic.


int GetNumberOfHole s(void) const;

int GetColour(void) const;
"unidiomati c" is a subjective term.
};

What do yous think of the following:
class Cheese
{
private:

int number_of_holes ;

int colour;

public:

const int& GetNumberOfHole s(void)
{
return number_of_holes ; }

const int& GetColour(void)
{
return colour; }


I think those should be const functions, too, and you don't need the
"void".

const int& GetNumberOfHole s(void) const;

const int& GetColour(void) const;

I am fully aware that I don't need the "void".
};

int main(void)
{
Cheese chalk;

chalk.GetNumber OfHoles();
Pointless. Didn't you mean

something = chalk.GetNumber OfHoles();

No.

I didn't suggest there was a point.


? There's an important difference.
}
I wonder was so many books think they have to show you the stupid way
before they give you the lean, mean, efficient way.
Because it's the safe way? Once you start returning references, the
next thing is to try returning references to temporaries, with
hilarious consequences.

Hence the absence of the returning of references to temporaries.

What do you think you would gain by returning a reference?

I doubt that returning an int by value is likely to be any more obese
or less efficient than returning a const reference. Even if you'd
substituted some class with a costly copy constructor, don't forget
that ultimately you want to _do_ something with the value of whatever
the function returns, or why call it in the first place? And that
means that somewhere or other there's likely to be a copy operation
anyway, whether you return a value or a reference. Given the existence
of return value optimisation, the difference in cost may be less than
you expected.

If I'm pedantic about it, there's greater probability of the reference form
being more efficent than the return-by-value form, as the return-by-value
form, under the duress of the Standard, *may* create a temporary.
-JKop

Jul 22 '05 #9
Karl Heinz Buchegger posted:
and when the internals of that class Cheese change, all the code that
uses that class breaks immediatly. Congratulations : you just found a
clever way of breaking the concept of encapsulation :-)

Trust your compilers optimizer!
He may do more then you expect.

So long as you have read-only variables/objects, it should be grand.
-JKop
Jul 22 '05 #10

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

Similar topics

2
8999
by: Gunnar | last post by:
Hello, I've just written a CPP program that reads integers from a binary file, and used this code while (my_ifstram.read( (char* ) &number, sizeof(int)) { // do something with number } My question is now, where can I find a manual that describes what the read method does with the ifstream object? I'm sitting here with my Linux/Debian machine, but I have not found any
6
3471
by: Steve | last post by:
Hi, I'm trying to convert a file reading loop into one using streams. The BSD OS read API returns the number of bytes read, but istream::read returns itself. How can I find out the number of bytes actually read? What the code fragment should do is read up to 1000 bytes into a buffer, or finish early if reading failed. Just your average read loop. I have: (this is a simplified version; I know there's no detailed error
12
11659
by: Steven T. Hatton | last post by:
I know of a least one person who believes std::ifstream::read() and std::ofstream::write() are "mistakes". They seem to do the job I want done. What's wrong with them. This is the code I currently have as a test for using std::ifstream::read(). Is there anything wrong with the way I'm getting the file? #include <vector> #include <iomanip> #include <fstream> #include <iostream>
2
3088
by: Sandman | last post by:
Just looking for suggestion on how to do this in my Web application. The goal is to keep track of what a user has and hasn't read and present him or her with new material I am currently doing this by aggregating new content from all databases into a single indexed database and then saving a timestamp in the account database (for the current user) that tells me when the user last read items in the aggregated database.
2
2505
by: Andrea Bauer | last post by:
Hallo, wie kann ich so eine Datei unter .Net schreiben C++ oder C#. Bitte mit Funktionsaufrufen. Vielen Dank. Grüße Andrea <Product> <ProgramNumber>2</ProgramNumber>
4
3844
by: Ollie Cook | last post by:
Hi, I am having some difficulty with read(2) and interrupting signals. I expect I am misunderstanding how the two work together, so would appreciate some guidance. I am trying to 'time out' a socket read after a certain delay. The logic is (I will provide a test program below): - create and connect socket
1
3998
by: Jose Reckoner | last post by:
I'm running python 2.3 on Windows XP. Anyone have a quick small script to convert .DT1 and .DEM data to ASCII or some other format? I don't need a viewer. Thanks!
0
4748
by: phplasma | last post by:
Hey, I am currently attempting to implement a multi-threaded C# socket, using SSL (.pem file/certification/private key combo) server using Visual Studio C# Express. I have successfully made the client application establish a connection, and send data, which appears in plain, de-crypted text on the server - this works.
4
2800
by: zl2k | last post by:
hi, there I have a appendable binary file of complex data structure named data.bin created by myself. It is written in the following format: number of Data, Data array Suppose I have following data.bin (3 Data appended to 2 Data): 2, data0, data1, 3, data0, data1, data2
5
12865
by: Thomas Christensen | last post by:
This issue has been raised a couple of times I am sure. But I have yet to find a satisfying answer. I am reading from a subprocess and this subprocess sometimes hang, in which case a call to read() call will block indefinite, keeping me from killing it. The folloing sample code illustrates the problem: proc = subprocess.Popen(,
0
8737
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
9232
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
8978
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
8936
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
7827
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...
0
5905
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();...
1
3104
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2036
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.