bug-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Possible bug in conversion operator


From: Wojciech Komornicki
Subject: Possible bug in conversion operator
Date: Thu, 30 Nov 2000 06:11:04 -0600 (CST)

I have come accross a compiler bug when using a conversion operator
from a user-defined type to a user defined type. Specifically, I have
declared two classes 

    class MyComplex
    {
    private:
        double re;
        double im;
    public:
        MyComplex() : re(0), im(0) {}
        MyComplex(double _re) : re(_re), im(0) {}
        MyComplex(double _re, double _im) : re(_re), im(_im) {}

        // accessor methods
        double real() { return re; }
        double imaginary() { return im; }

        // friend functions
        friend MyComplex operator+(MyComplex z, MyComplex w);
        friend MyComplex operator-(MyComplex z, MyComplex w);
        friend MyComplex operator*(MyComplex z, MyComplex w);
        friend MyComplex operator/(MyComplex z, MyComplex w);
        friend ostream& operator<<(ostream&, MyComplex z);
        friend istream& operator>>(istream&, MyComplex& z);
    };

    class Token {
    public:
        char ch;
        MyComplex z;
        Token() : z(0) { ch = 0; }
        operator MyComplex() const;
        operator char() const;
    };

The compiler rejects the code:

    Token t;
    MyComplex a;

    ...

    a = MyComplex(t);

thinking that a constructor is being invoked in the assignment and not
the conversion operator. Since there is no constructor for Complex
from a Token, the compler generates an error.  No error is reported
for the similar code:

    Token t;
    char ch;

    ...

    ch = char(t);

(The reason I came across this was because I wanted to create a simple
example of a conversion operator for my students.)

I have tried this on other compilers to which I have access (SUN C++
compiler and several generations of Borland C++ compilers) and no
errors or warnings are generated by those compilers.

-- 
Wojciech Komornicki                                        Dept of Mathematics
address@hidden                                      Hamline University
                                                             St Paul, MN 55104
                                                                           USA



reply via email to

[Prev in Thread] Current Thread [Next in Thread]