Conversion Operator question

Discussion in 'C++' started by Bill97, Mar 11, 2005.

  1. Bill97

    Bill97 Guest

    In my code below, the conversion operator is invoked implicitly (and
    explicitly) in main(). In the first case, the address value is output--in
    the later cases the character string pointed to by the address is output.

    I am looking for a satisfying answer as to why the character string isn't
    output in the first of the 3 cases? Thank you for your reply


    class String
    {
    public:
    String(char * s)
    {
    strcpy(A, s);
    }

    operator char *()
    {
    cout << "conv. op. called" << endl;
    return A;
    }

    private:
    char A[100];
    };


    int main()
    {

    String pet("cat");

    cout << pet << endl;

    cout << (( char *)pet) << endl;

    cout << static_cast< char *>(pet) << endl;


    return 0;
    }
     
    Bill97, Mar 11, 2005
    #1
    1. Advertising

  2. It is printed. Here is what I get when I run this..

    conv. op. called
    cat
    conv. op. called
    cat
    conv. op. called
    cat

    g++ 3.4.2
     
    Raghu Uppalli, Mar 11, 2005
    #2
    1. Advertising

  3. Bill97

    Bill97 Guest

    "Raghu Uppalli" <> wrote in message
    news:...
    > It is printed. Here is what I get when I run this..
    >
    > conv. op. called
    > cat
    > conv. op. called
    > cat
    > conv. op. called
    > cat
    >
    > g++ 3.4.2
    >

    Thanks for letting me know that. That was what I wanted to get. Using MS
    Visual Studio 6.0, I got an address, followed by two cats. Conversion
    operator was called all 3 times.

    The only explanation I can think of is that perhaps a char* value is
    converted to some type of string object (and only one conversion can be
    applied).
     
    Bill97, Mar 11, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. hunter hou

    conversion operator question

    hunter hou, Feb 10, 2006, in forum: C++
    Replies:
    1
    Views:
    344
    Alf P. Steinbach
    Feb 10, 2006
  2. Arvid Requate
    Replies:
    2
    Views:
    993
    Alf P. Steinbach
    Jun 23, 2006
  3. hurcan solter
    Replies:
    3
    Views:
    733
    Cholo Lennon
    Aug 29, 2007
  4. , India
    Replies:
    2
    Views:
    479
    Fraser Ross
    Sep 15, 2009
  5. cronusf
    Replies:
    12
    Views:
    496
Loading...

Share This Page