type casting object to int?

This is a discussion on type casting object to int? within the C++ Programming forums, part of the General Programming Boards category; hi Guys, well i have a small issue (i think). i have a class that only contains one variable and ...

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    28

    type casting object to int?

    hi Guys,

    well i have a small issue (i think). i have a class that only contains one variable and i was wondering if i could assign an object of this class, to a variable of the same type as it's only data member by type casting this class. (among other things) i have tried the following but i get compile errors:

    Code:
    class A
    {
    private:
      int a;  
    };
    
    int main(int argc, char* argv[])
    {
      A objA;
    
      int b;
      b = (int)objA;
    
      return 0;
    }
    with reinterpret_cast also doesn't work:
    Code:
    b = reinterpret_cast<int>(objA);
    can it be done?
    Last edited by symbiote; 03-14-2009 at 06:30 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,973
    If you want to allow conversion to int, provide a conversion function, i.e., operator int(). If implicit conversion is undesirable (and it often is undesirable), then provide a named function that returns an int instead of a conversion function.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    28
    interesting.
    thanks again laserlight (problem solved)

    Greetings
    Last edited by symbiote; 03-14-2009 at 10:48 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Replies: 1
    Last Post: 10-27-2006, 01:21 PM
  4. Converted from Dev-C++ 4 to Dev-C++ 5
    By Wraithan in forum C++ Programming
    Replies: 8
    Last Post: 12-03-2005, 06:45 AM
  5. Learning OpenGL
    By HQSneaker in forum C++ Programming
    Replies: 7
    Last Post: 08-06-2004, 08:57 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21