Overloaded cast?

This is a discussion on Overloaded cast? within the C++ Programming forums, part of the General Programming Boards category; Hello, Is there a way to overload the way my class is casted to another object? For example, this is ...

  1. #1
    Registered User
    Join Date
    Jun 2002
    Posts
    132

    Question Overloaded cast?

    Hello,
    Is there a way to overload the way my class is casted to another object? For example, this is my class:
    Code:
    class CClass1
    {
    public:
       Class1(int num) { i = num; }
       blah blah
    
    private:
        int i;
    };
    
    CClass1 c (5);
    int casted = (int)c;
    So in that case, i would want the 'casted' to have the value of the integer member in CClass1. Is it possible in c++?
    Thanks
    Y3K Network http://www.y3knetwork.com
    Bringing the software of the future on the net.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,794
    I think you do something like this, I may be wrong:

    Code:
    class CClass1
    {
    public:
        Class1(int num) { i = num; }
        operator int()
        {
            return i;
        }
    
    private:
        int i;
    };
    
    CClass1 c (5);
    int casted = (int)c;
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Including The Right DLLs
    By bumfluff in forum Game Programming
    Replies: 8
    Last Post: 12-28-2006, 02:32 AM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  3. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  4. errors in class(urgent )
    By ayesha in forum C++ Programming
    Replies: 1
    Last Post: 11-10-2001, 09:14 PM
  5. errors in class(urgent)
    By ayesha in forum C++ Programming
    Replies: 2
    Last Post: 11-10-2001, 05:51 PM

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