Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator issue

I'm having some trouble with using the conditional operator to get a reference to an object. I have the a setup similar to this:

class D
{
    virtual void bla() = 0;
};

class D1 : public D
{
    void bla() {};
};

class D2 : public D
{
    void bla() {};
};

class C
{
public:
    C()
    {
        this->d1 = new D1();
        this->d2 = new D2();
    }

    D1& getD1() {return *d1;};
    D2& getD2() {return *d2;}
private:
    D1 *d1;
    D2 *d2;
};

int main()
{    
    C c;    
    D& d = (rand() %2 == 0 ? c.getD1() : c.getD2());    
    return 0;    
}

When compiling, this gives me the following error:

WOpenTest.cpp: In function 'int
main()': WOpenTest.cpp:91: error: no
match for conditional 'operator?:' in
'((((unsigned int)rand()) & 1u) == 0u)
? c.C::getD1() : c.C::getD2()'

I understand this is illegal according to the C++ standard (as seen in this blog post), but I don't know how to get my reference to D without using the conditional operator.

Any ideas?

like image 462
laura Avatar asked Nov 27 '09 08:11

laura


People also ask

What is the conditional operator in C++?

The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible. Syntax: The conditional operator is of the form. variable = Expression1 ? Expression2 : Expression3.

What is the difference between a conditional operator and if-else?

A conditional operator is a single programming statement, while the 'if-else' statement is a programming block in which statements come under the parenthesis. A conditional operator can also be used for assigning a value to the variable, whereas the 'if-else' statement cannot be used for the assignment purpose.

What is the conditional operator in ASL?

As conditional operator works on three operands, so it is also known as the ternary operator. The behavior of the conditional operator is similar to the ' if-else ' statement as 'if-else' statement is also a decision-making statement.

Why conditional operators are called ternary operators?

Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary operators. Here, Expression1 is the condition to be evaluated.


2 Answers

Cast to D& within both branches:

D& d = (rand() %2 == 0 ? static_cast<D&>(c.getD1()) : static_cast<D&>(c.getD2()));
like image 141
Johannes Schaub - litb Avatar answered Sep 20 '22 07:09

Johannes Schaub - litb


Btw, you don't really need to use a conditional operator,

D* dptr; if(rand() %2 == 0) dptr = &c.getD1(); else dptr = &c.getD2();
D& d = *dptr;

would work too.

like image 38
Murali VP Avatar answered Sep 23 '22 07:09

Murali VP