473,396 Members | 1,853 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

const references : confusion

raj
I need explanation of the behavior of the following code. When run as it is, it gives error.

//-------------------------<start>------------------
#include <iostream.h>
#include <stdlib.h>

class ABC
{
private: int x;

public:
ABC() { x=0; }
ABC (int a) { x=a; }
ABC (const ABC& abc)
{
x=abc.x+1; //increasin by 1 just as a token of copy constructor invocation
cout<<"\n\tCopy constructor invoked.";
}

ABC& operator=(ABC& abc) //NO ERROR IF CHANGED TO : ABC& operator=(const ABC& abc)
{ //line 18
x=abc.x;
return (*this);
}
ABC friend frnd_func();
};

ABC frnd_func()
{
ABC abc(100);
return abc;
}

int main()
{
ABC a1(5);
ABC a2=a1; //just to test copy constructor.
a2=frnd_func(); //gives error : "initialisation of non-const reference type 'cxlass ABC&'
// from rvalue of typpe 'ABC' in passing argument 1 of 'ABC::operator=(ABC&)'
cout<<"\n\n";system("PAUSE");
return 0;
}
//-------------------------<end>---------------------

Running it in Bloodshed Dev C++ gives the following error:
35: Initialisation of non-const reference type 'class ABC&'
35: from rvalue of type 'ABC'
18: in assigning argument 1 of 'ABC::operator=(ABC &)'

But, if I change the = overloading declaration to:
ABC& operator=(const ABC& abc)
then the error vanishes.

Why should i need to add the 'const' keyword here?

Jul 22 '05 #1
7 1368
In expression:
a2=frnd_func();
frnd_funct() creates a temporary object ABC that is assigned to a2.
All temporary objects are const (you cannot change them), so the
operator: ABC& operator=(ABC& abc) has to take a const reference to
assign temporary object.

regareds
q

http://members.lycos.co.uk/ququqa2/

raj wrote:
I need explanation of the behavior of the following code. When run as it is, it gives error.

//-------------------------<start>------------------
#include <iostream.h>
#include <stdlib.h>

class ABC
{
private: int x;

public:
ABC() { x=0; }
ABC (int a) { x=a; }
ABC (const ABC& abc)
{
x=abc.x+1; //increasin by 1 just as a token of copy constructor invocation
cout<<"\n\tCopy constructor invoked.";
}

ABC& operator=(ABC& abc) //NO ERROR IF CHANGED TO : ABC& operator=(const ABC& abc)
{ //line 18
x=abc.x;
return (*this);
}
ABC friend frnd_func();
};

ABC frnd_func()
{
ABC abc(100);
return abc;
}

int main()
{
ABC a1(5);
ABC a2=a1; //just to test copy constructor.
a2=frnd_func(); //gives error : "initialisation of non-const reference type 'cxlass ABC&'
// from rvalue of typpe 'ABC' in passing argument 1 of 'ABC::operator=(ABC&)'
cout<<"\n\n";system("PAUSE");
return 0;
}
//-------------------------<end>---------------------

Running it in Bloodshed Dev C++ gives the following error:
35: Initialisation of non-const reference type 'class ABC&'
35: from rvalue of type 'ABC'
18: in assigning argument 1 of 'ABC::operator=(ABC &)'

But, if I change the = overloading declaration to:
ABC& operator=(const ABC& abc)
then the error vanishes.

Why should i need to add the 'const' keyword here?


Jul 22 '05 #2

"ququqa" <qu*****@aster.pl> wrote in message
news:c0***********@mamut.aster.pl...
In expression:
a2=frnd_func();
frnd_funct() creates a temporary object ABC that is assigned to a2.
All temporary objects are const (you cannot change them),


That is not true, for instance

X func();

X x;
func() = x;

is perfectly legal code (assuming X is a class, and assignment of X is
legal). The return value from func is a temporary, but it is not const.

The correct rule is that you cannot bind a non-const reference to a
temporary object.

This subject gets a lot of coverage in this group because it seems a lot of
people are surprised by this rule.

john
Jul 22 '05 #3
>
Running it in Bloodshed Dev C++ gives the following error:
35: Initialisation of non-const reference type 'class ABC&'
35: from rvalue of type 'ABC'
18: in assigning argument 1 of 'ABC::operator=(ABC &)'

But, if I change the = overloading declaration to:
ABC& operator=(const ABC& abc)
then the error vanishes.

Why should i need to add the 'const' keyword here?


Rules of C++, you cannot bind a temporary object to a non-const reference.
The return value of a function is a temporary.

john
Jul 22 '05 #4

"John Harrison" <jo*************@hotmail.com> wrote in message
news:c0*************@ID-196037.news.uni-berlin.de...

Running it in Bloodshed Dev C++ gives the following error:
35: Initialisation of non-const reference type 'class ABC&'
35: from rvalue of type 'ABC'
18: in assigning argument 1 of 'ABC::operator=(ABC &)'

But, if I change the = overloading declaration to:
ABC& operator=(const ABC& abc)
then the error vanishes.

Why should i need to add the 'const' keyword here?


Rules of C++, you cannot bind a temporary object to a non-const reference.
The return value of a function is a temporary.

True and it's good that your compiler has pointed it out to you.
There are compilers (with options) which as a language extension allow binding
temporary objects
to non-const references. So if such an option is set/unset you may just write
non-standard code without even realizing it.
E.g. On VC++ compile without /Za compiler option your code would run just fine.

-Sharad
Jul 22 '05 #5
raj
Thanks a lot ... that clears up the matter (and some others too).
:)

Jul 22 '05 #6
raj
(tho i dont undestand why the compiler shd take such pains to ensure the constness of temporary objects... particularly, whn i'm takin control of them using copy constructors)

Jul 22 '05 #7

"raj" <re*******@yahoo.co.in> wrote in message
news:41******************************@localhost.ta lkaboutprogramming.com...
(tho i dont undestand why the compiler shd take such pains to ensure the constness of temporary objects... particularly, whn i'm takin control of
them using copy constructors)


Jesus, how many times does this have to be said.

Temporary objects are not const, the compiler does not enforce the constness
of temporary objects.

There is a recent thread 'non-const function return values: gcc bug or
language flaw' which goes into this in great detail and concludes with the
real reason for this rule, contributed by the great man himself (Bjarne
Stroustrup).

john
Jul 22 '05 #8

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

Similar topics

39
by: JKop | last post by:
Back when I read my first C++ book, I was given the following scenario: class Cheese { public: int number_of_holes; int colour;
4
by: cppsks | last post by:
I have been working on making a constant array available for the clients. However, it is placing it in the text segment, and external references result in unresolved references to the array. Taking...
1
by: Andrew R. Thomas-Cramer | last post by:
C#, like Java, fails to provide a const-qualifier for references for compile-time const checking. In Java, I used to document intended const-qualified references (e.g., method parameters) with...
2
by: vineoff | last post by:
When you should not or can't use const references? Like void f ( const Foo& b) ; or int main() { const int& r = 5; }
1
by: Richard Lewis Haggard | last post by:
I'm having a problem with what appears to be some sort of confusion with references. I have a single solution with a dozen projects which has been working quite nicely for a while. The references...
8
by: Michael Safyan | last post by:
Dear members of comp.lang.c++, I am a little bit confused about the differences between constant references and values. I understand that it is faster to use a constant reference ("const T&") than...
0
by: d3x0xr | last post by:
Heh, spelled out in black and white even :) Const is useles... do NOT follow the path of considering any data consatant, because in time, you will have references to it that C does not handle,...
7
by: siddhu | last post by:
Dear Experts, I have a question. I wrote the following code class A { public: void g(){}
10
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
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,...

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.