S
subramanian100in
Consider the following program:
#include <cstdlib>
#include <iostream>
using namespace std;
class Test
{
public:
// I have not made this ctor 'explicit' for learning purpose only
inline Test(int arg = 10);
Test &operator=(const Test &arg);
private:
int val;
};
inline Test::Test(int arg) : val(arg)
{
cout << "from test one arg ctor: " << val << endl;
}
Test &Test:
perator=(const Test &arg)
{
if (this != &arg)
{
val = arg.val;
cout << "Test:
perator=() called: " << val << endl;
}
return *this;
}
Test fn()
{
return Test();
}
int another()
{
int x = 100;
return x;
}
int main()
{
fn() = -1;
//another() = 100;
return EXIT_SUCCESS;
}
The above program compiles fine. However if I remove the comment
for the line
//another() = 100;
then I get compilation error
error: non-lvalue in assignment
The difference is that in 'fn() = -1', the function 'fn()' returns a
temporary object of user-defined type and so this temporary object
occupies a region of storage and therefore, it can be used as an
lvalue. However in the expression
another() = 100;
another() returns a built-in type value and hence cannot be used as an
lvalue.
Is my understanding correct ?
Thanks
V.Subramanian
#include <cstdlib>
#include <iostream>
using namespace std;
class Test
{
public:
// I have not made this ctor 'explicit' for learning purpose only
inline Test(int arg = 10);
Test &operator=(const Test &arg);
private:
int val;
};
inline Test::Test(int arg) : val(arg)
{
cout << "from test one arg ctor: " << val << endl;
}
Test &Test:
{
if (this != &arg)
{
val = arg.val;
cout << "Test:
}
return *this;
}
Test fn()
{
return Test();
}
int another()
{
int x = 100;
return x;
}
int main()
{
fn() = -1;
//another() = 100;
return EXIT_SUCCESS;
}
The above program compiles fine. However if I remove the comment
for the line
//another() = 100;
then I get compilation error
error: non-lvalue in assignment
The difference is that in 'fn() = -1', the function 'fn()' returns a
temporary object of user-defined type and so this temporary object
occupies a region of storage and therefore, it can be used as an
lvalue. However in the expression
another() = 100;
another() returns a built-in type value and hence cannot be used as an
lvalue.
Is my understanding correct ?
Thanks
V.Subramanian