Can a conditional statement return a link?

I stumbled upon a line of code and never thought this might work. I thought that the conditional operator returns a value and does not work with a link.

Some pseudo codes:

#include <iostream> using namespace std; class A { public: A(int input) : v(input) {}; void print() const { cout << "print: " << v << " @ " << this << endl; } int v; private: //AA(const A&); //A operator=(const A&); }; class C { public: C(int in1, int in2): a(in1), b(in2) {} const A& getA() { return a;} const A& getB() { return b;} A a; A b; }; int main() { bool test = false; C c(1,2); cout << "A @ " << &(c.getA()) << endl; cout << "B @ " << &(c.getB()) << endl; (test ? c.getA() : c.getB()).print(); // its working } 

Can someone explain? thanks.

+4
source share
1 answer

Your assumption of a conditional statement is incorrect. An expression type is any type that c.getA() and c.getB() , if they are of the same type, and if they denote lvalues, then the whole expression. (The exact rules are given in ยง5.16 of the C ++ standard.)

You can even do this:

 (condition? a: b) = value; 

conditionally set either a or b to value . Note that this is C ++ - specific; in C, the conditional operator does not denote an l-value.

+10
source

All Articles