Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uunet!bywater!arnor!watson!blinn.watson.ibm.com!mittle From: mittle@blinn.watson.ibm.com (Josh Mittleman) Newsgroups: comp.lang.c++ Subject: Re: Pointers to sibling classes in conditional expressions Message-ID: <1991Apr26.152511.14662@watson.ibm.com> Date: 26 Apr 91 15:25:11 GMT References: Sender: @watson.ibm.com Distribution: comp Organization: IBM T. J. Watson Research Lines: 47 In article , robertk@lotatg.lotus.com (Robert Krajewski) writes: > I have a function that returns a pointer to a parent class -- it looks > at its arguments, and then makes a new object (with new) either of > child class A, or B, depending on the arguments to this function. The > decision is made in a conditional expression, and the result is > returned: > > Parent * MakeIt(...) > { > ... > return ( ? new A(...) : new B(...) ); > } > > g++ warns that the two expressions are of different types, and so does > MPW C++. My initial reaction was that this is a compiler error. ARM, p.78, lays out the rules for correctly formed conditional expressions: "If both the second and the third expressions are of arithmetic type, the usual arithmetic conversions are performed to bring them to a common type. Otherwise, if both the second and the third expressions are either a pointer or a constant expression that evaluates to 0, pointer conversions are performed to bring them to a common type. Otherwise, if both the second and the third expressions are either references, reference conversions are performed to bring them to a common type. Otherwise if both the second and the third expressions are void, the common type is void. Otherwise if both the second and the third expressions are the same class T, the common type is T. Otherwise the expression is illegal." I tried the following code, and got the same kind of error from the ATT v2.1 compiler. I still think it looks right. Anybody see something that I missed? class Parent { }; class A : public Parent { public: A(int); }; class B : public Parent { public: B(int); }; Parent* F(int i) { return (i ? new A(i) : new B(i)); // error: type mismatch: A * ?: B * }