Contradictory behaviour of temporary objects

S

sachingoel82

Hi All,

I find following C++ behaviour regarding temporary objects quite
contradictory. Consider this:

class A
{
...

public:
void bar () { ... } // non-const member function
};

A getA () { ... } // return an object

void foo (A& a) { ... }

int main ()
{
foo (getA ()); // error: not allowed to pass temporary object as
non-const reference. acceptable.

getA ().bar (); // why is this allowed ?? calling a non-const
functrion on a temporary object ?
}

Any ideas why it could be so ?

If passing a temporary object as non-const reference is not allowed
because making changes to it doesn't make sense, doesn't same thing
apply to calling non-const member function on a temporary ?
 
?

=?ISO-8859-1?Q?Erik_Wikstr=F6m?=

Hi All,

I find following C++ behaviour regarding temporary objects quite
contradictory. Consider this:

class A
{
...

public:
void bar () { ... } // non-const member function
};

A getA () { ... } // return an object

void foo (A& a) { ... }

int main ()
{
foo (getA ()); // error: not allowed to pass temporary object as
non-const reference. acceptable.

getA ().bar (); // why is this allowed ?? calling a non-const
functrion on a temporary object ?
}

Any ideas why it could be so ?

If passing a temporary object as non-const reference is not allowed
because making changes to it doesn't make sense, doesn't same thing
apply to calling non-const member function on a temporary ?

No, this has nothing to do with what you can and can not do with
temporary objects, but rather what you can and can not do with
references. A temporary object is just like any other object. However
you can not bind a non-const reference to a temporary since there's a
possibility that you'd end up with stale references (ie. the reference
is still there when the temporary is not).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top