473,804 Members | 2,673 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 : "initialisa tion of non-const reference type 'cxlass ABC&'
// from rvalue of typpe 'ABC' in passing argument 1 of 'ABC::operator= (ABC&)'
cout<<"\n\n";sy stem("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 1385
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 : "initialisa tion of non-const reference type 'cxlass ABC&'
// from rvalue of typpe 'ABC' in passing argument 1 of 'ABC::operator= (ABC&)'
cout<<"\n\n";sy stem("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*******@yaho o.co.in> wrote in message
news:41******** *************** *******@localho st.talkaboutpro gramming.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
3101
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
2850
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 the const off the definition solves the problem (the variable is placed in the data segment). Is this how const globals are supposed to work, or did the linker screw up? Thanks.
1
1268
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 C++ syntax: "const*". Does anyone have a better suggestion, for C#? The best I've come up with is "OBJECT READONLY", but that overloads an existing C# keyword that means something else.
2
1664
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
3182
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 between projects in the solution were established through project references, not by browsing to an assembly DLL. All of the projects are strongly named and use key files. Each project's AssemblyInfo.cs specifies the assembly version, where the...
8
4099
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 a value ("T") since the former does not require copying whereas the latter does, is that correct? Also, I un derstand that "const T&" allows for polymorphism whereas "T" will generate code cuttting. On the former points, I am fairly confident......
0
1878
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, and you'll be left with just noisy compiler warnings and confusion. if you start a project with all char *, and char ** and even char ***, if you begin at the low level weeding out references of 'passing const char * to char * ( such as...
7
1540
by: siddhu | last post by:
Dear Experts, I have a question. I wrote the following code class A { public: void g(){}
10
4026
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
9577
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
10325
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...
0
10075
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...
1
7615
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
5519
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
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4295
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
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
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.