Thread: operator int()

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    1

    operator int()

    what does operator int () in c++ class signifies. I came across a class shown below:

    Code:
    class Foo
      {
        public:
          Foo (int);
          operator int ();
          operator double ();
        private:
          int member_;
      };
    
      Foo::Foo (int member)
        : member_ (member)
      {
        ;
      }
    
      Foo::operator int()
      {
        return member_;
      }
    
      Foo::operator double()
      {
        return 1.0 * member_;
      }
    whats the purpose of defining operator int and operator float. As far as i remember C++ prohibits overloading c++ keywords. then how does the above program c\ompiles and works?

  2. #2
    C++ Newbie
    Join Date
    Nov 2005
    Posts
    49
    Operators are different from keywords, those are conversion operators used to return an equivalent object of one type from another. Kind of like typecasting.

    I guess aside from typecasting, all other keywords cannot be overloaded. Since int or double are types, they can be used in conversion operators. Like new and delete for memory.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    An Foo:perator X() (where X is a type) is a conversion operator from Foo to X. There is no constraint that the type be a basic type (int, float, etc). It is also possible to provide conversions to class types by the same means.

    So;
    Code:
    //   declaration of Foo from above
    
    int main()
    {
          Foo x(42);
    
          int y = x;    // will invoke  Foo::operator int(), so y will get a value of 42
    
          float z = x;   // will invoke Foo::operator float() so y will get a single-precision value of 42.0
    
         y = (int)x;    // explicitly invokes Foo::operator int()
         
    }

Popular pages Recent additions subscribe to a feed