Thread: About conversion operator

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    129

    About conversion operator

    What does a conversion operator excatly does, more precisely what does it return? Before going any further read this

    Code:
    #include <stdio.h>
    
    #define BUG
    
    class Foo
    {
      private:
    	short int bar;
    #ifdef BUG
      char c;
    #endif
      public:
    	Foo() :
    		bar(100)
    #ifdef BUG
    		,c(12)
    #endif
    		{}
    	operator short int () { return bar; }
    };
    
    void foobar(short int n)
    {
    	printf("%d\n", n);
    }
    
    int main()
    {
    	Foo foo;
    	printf("%d\n", foo);
    	foobar(foo);
    	return 0;
    }
    output while compiling:
    G:\source\test>gxx foobar.cpp -Wall
    foobar.cpp: In function `int main()':
    foobar.cpp:32: warning: int format, Foo arg (arg 2)

    output while BUG is not defined:
    100
    100

    and when BUG is defined
    786532
    100

    So, all works fine if I don't declare `c' but that's not the case. It's also quite surprising how `foobar()' works just fine in both times and direct `printf()' call doesn't. So it must be because stdarg.h that printf is using in it's declaration, right?

    Anyway, is there any way to retrieve the value of `bar' so that a) it works if `c' is declared and most important b) it doesn't give me a warning ie. to do it as supposed? All this without ``short int GetBar() const { return bar; }'' of course.
    Last edited by kooma; 12-31-2001 at 12:24 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Header File Question(s)
    By AQWst in forum C++ Programming
    Replies: 10
    Last Post: 12-23-2004, 11:31 PM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM