473,785 Members | 2,738 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regarding Temporary objects and const-ness !

Consider the following codes:

class abc
{
int i;

public:
abc() : i(0) {}
void func() { .....some code....}
};

void func2(const abc& Obj)
{
.....some code...
}
int main()
{
func2(12);..... ..............//CALL 1

const abc obj;
obj.func();.... ..............// CALL 2

abc().func();.. .............// CALL 3

return 0;
}

CALL 1 takes place fine by implicit conversion of 5 to an abc object.
But, if the func2() paramater is kept non-const, then it gives
error !! WHY??

CALL2 doesn't take place because we are calling a non-const function
on a const object. That's understood.

If you say that the reason for CALL 1 not taking place in case of non-
const function parameter is that the temporary object created is a
const, then what is the reason for CALL 3 taking place successfully??

I'm really confused regarding this problem.
Are temporary objects const??
If not, then why do we need the prototype of func2 as reference to a
const?
Nov 6 '08 #1
5 2651
co************* *@gmail.com wrote:
Consider the following codes:

class abc
{
int i;

public:
abc() : i(0) {}
void func() { .....some code....}
};

void func2(const abc& Obj)
{
.....some code...
}
int main()
{
func2(12);..... ..............//CALL 1

const abc obj;
obj.func();.... ..............// CALL 2

abc().func();.. .............// CALL 3

return 0;
}

CALL 1 takes place fine by implicit conversion of 5 to an abc object.
But, if the func2() paramater is kept non-const, then it gives
error !! WHY??
In the code you supplied CALL 1 won't compile. Please make
sure you provide code we can paste and compile to observe
what you claim to see. (That's an FAQ. Please take the time
to read and understand the relevant portions of the FAQ
before you ask here.)

Assuming you have 'abc::abc(int)' forgotten to paste, but
have it in your real code: A ctor taking one argument (or
taking more, but the other's are optional) which isn't
marked as 'explicit' is an user-defined implicit conversion
operator. If, where an 'abc' is needed, you supply something
else, and if it takes only one user-defined conversion, the
compiler will employ such ctors to perform the conversion.
Thus, 'func2(12)' is converted to 'func1(abc(12)) ' and this
is fine, since the compiler can bind temporaries to const
references. If, however, 'func2()' takes a non-const reference
it won't compile, because it isn't allowed to bind temporaries
to non-const references.
CALL2 doesn't take place because we are calling a non-const function
on a const object. That's understood.

If you say that the reason for CALL 1 not taking place in case of non-
const function parameter is that the temporary object created is a
const, then what is the reason for CALL 3 taking place successfully??
The temporary isn't 'const'. It's an rvalue. You can call member
functions, even non-const ones, on rvalues of user-defined types
(even though you cannot modify rvalues of built-in types).
I'm really confused regarding this problem.
Are temporary objects const??
If not, then why do we need the prototype of func2 as reference to a
const?
HTH,

Schobi
Nov 6 '08 #2
I'M EXTREMELY SORRY EVERYONE

The class also defines a parametrized constructor :

class abc
{
int i;
public:
abc() : i(0) {}
abc(int x) : i(x) {}
void func() { .....some code....}
};

Please review the question!!
Nov 6 '08 #3
co************* *@gmail.com wrote:
I'M EXTREMELY SORRY EVERYONE

The class also defines a parametrized constructor :

class abc
{
int i;
public:
abc() : i(0) {}
abc(int x) : i(x) {}
void func() { .....some code....}
};
This still doesn't compile.
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8
Please review the question!!
I've already answered your question assuming the above ctor.

Schobi
Nov 6 '08 #4
On Thu, 06 Nov 2008 07:45:06 -0800, coolguyaroundyo u wrote:
I'M EXTREMELY SORRY EVERYONE

The class also defines a parametrized constructor :

class abc
{
int i;
public:
abc() : i(0) {}
abc(int x) : i(x) {}
void func() { .....some code....}
};

Please review the question!!
Review what question?

--
OU
Remember 18th of June 2008, Democracy died that afternoon.
http://frapedia.se/wiki/Information_in_English
Nov 6 '08 #5
On Nov 6, 4:22 am, coolguyaround.. .@gmail.com wrote:
Consider the following codes:

class abc
{
int i;

public:
abc() : i(0) {}
void func() { .....some code....}

};

void func2(const abc& Obj)
{
....some code...

}

int main()
{
func2(12);..... ..............//CALL 1

const abc obj;
obj.func();.... ..............// CALL 2

abc().func();.. .............// CALL 3

return 0;

}

CALL 1 takes place fine by implicit conversion of 5 to an abc object.
But, if the func2() paramater is kept non-const, then it gives
error !! WHY??

CALL2 doesn't take place because we are calling a non-const function
on a const object. That's understood.

If you say that the reason for CALL 1 not taking place in case of non-
const function parameter is that the temporary object created is a
const, then what is the reason for CALL 3 taking place successfully??

I'm really confused regarding this problem.

Are temporary objects const??
If not, then why do we need the prototype of func2 as reference to a
const?
No, temporaries are rvalues. They are not constant and hence the
problem.
What prevents member function func(...) (in CALL 3) to modify the
temp?

Assuming a parametized constructor, fun2 needs a reference to constant
because the lifetime of the temporary needs to be extended.

func2(abc(12));

might fail if it were allowed to compile as is.

Look at it this way:

abc& r = abc();
r.func();

what guarantee do you have that the temporary isn't destroyed before
the second statement?
Well, the language does offer a guarentee.

const abc& r_ = abc();

extends the lifetime of the temporary until the reference_to_co nst
dies.

Nov 6 '08 #6

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

Similar topics

3
2285
by: kaede | last post by:
Hi all, Consider the following code fragment: // some data structure class Data { ... } // Container for the data structure Class Container {
19
2485
by: Kai-Uwe Bux | last post by:
Hi folks, I have trouble writing a class, derving from stringstream, that collects item and once it's done will write them to std::cout in one go. It works fine except when I use it as a temporary. Here is a tiny test programm: #include <iostream> #include <sstream>
5
1509
by: Andy Buckley | last post by:
Hi, A friend and I have recently had trouble getting code to compile when using temporary objects in constructors. A minimal example is below: This code fragment is used to construct seven ROD objects and run their doSomething() method (which is trivial). As far as we can tell, all seven methods should successfully construct a ROD object using temporary objects as constructor parameters, but using
5
1697
by: White Wolf | last post by:
Hi, I would like to double check how long a temporary returned by a function lives? Suppose I have an instance of a class type C, which has a member function returning some sort of wrapper-decorator by value - thereby creating an unnamed temporary. Assuming I start using the temporary (by calling its members) in the same expression, can I assume that it will live long enough to serve those calls?
9
10167
by: kiran.agashe | last post by:
Hi, Please refer program below: #include <string> #include <cstdio> using namespace std; const char* f(); main() {
3
3034
by: sven.suursoho | last post by:
Hello, In main(), the first output API is what I try to achieve. Unfortunately it fails, printing first string as pointer instead of human readable message. Tried to initialize str(""), set new buffer etc, but nothing worked. Ideas? Also might use another internal construct, only API is needed and requirement to reuse existing std::ostream inserters.
17
10283
by: Henning Hasemann | last post by:
I have a function which gets the adress of an object as argument. It does some comparsion with the object's contents and then returns. no Reference or pointer to the object is stored or will be used after the function has returned. Say the function whould be named f and the objects class whould be T it'll look like this: bool f(T* thing) { return thing->foobar == 5; // Just a stupid example
2
2399
by: perdubug | last post by:
Somebody told me that Tasking C166 C++ compiler has problems with temporary objects in function call parameters. He gave me below examples: Case 1:Wrong: rc = foo(&bar()); Case 2:Right: bar b; rc=foo(&b);
6
1518
by: thorsten.schilling | last post by:
Hello everybody, the question is, what is the "golden way" or the best way, if I have a memberfunction in a class, which should return a new instance of an object. For example some class Foo which holds a lot data and has the overloaded '+' operator and I want to do something like: //f1-f3 are all Foo instances f1 = f2+f3;
17
2102
by: Klaas Vantournhout | last post by:
Hi all, I was wondering if it is possible if you can check in a function if one of the arguments is temporary. What I mean is the following. A is a class, foo is a function returning a class and bar is a function using A is an argument returning something else class A;
0
9643
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
9480
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
10147
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
9947
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
8971
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
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
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
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.