Cast a struct ...

Discussion in 'C++' started by Konrad Mühler, May 20, 2008.

  1. Hi,

    I've a struct:

    struct POINT {
    int x,y;
    };

    And I want to commit a variable of type POINT in a function

    myFunction(POINT myVar) { ... }

    If I call the function, I want to write both values for x and y directly
    in the function call like :

    myFunction(POINT(1,2));

    This doesn't work and I want to know, how I can do this. Or do I have to
    define the struct as an independent class?

    Thanks
    Konrad
     
    Konrad Mühler, May 20, 2008
    #1
    1. Advertising

  2. > You can either define a constructor in your struct or define a
    > stand-alone function that would return a struct made from two arguments
    > (sort of out-of-the-class constructor):
    >
    > struct POINT {
    > int x,y;
    > POINT(int x_, int y_) : x(x_), y(y_) {} // constructor
    > };
    > ...
    > myFunction(POINT(1,2));
    >
    > or
    > POINT makePOINT(int x, int y) {
    > POINT p = { x, y };
    > return p;
    > }
    > ...
    > myFunction(makePOINT(1,2));
    >
    > Beware, that according to the current Standard, adding a user-defined
    > constructor prevents your class from being a POD. I think it's fixed in
    > the upcoming Standard. It actually may not mean anything different to
    > your program, but I just thought I'd mention it.


    Thank you very much. It helped a lot :)
    Konrad
     
    Konrad Mühler, May 20, 2008
    #2
    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. BestNews

    how to cast system.intptr to struct

    BestNews, Sep 2, 2003, in forum: ASP .Net
    Replies:
    1
    Views:
    4,761
    BestNews
    Sep 3, 2003
  2. MSG

    to cast or not to cast malloc ?

    MSG, Feb 6, 2004, in forum: C Programming
    Replies:
    38
    Views:
    1,082
    Dan Pop
    Feb 10, 2004
  3. EvilRix
    Replies:
    8
    Views:
    655
    Martin Dickopp
    Feb 14, 2004
  4. Chris Fogelklou
    Replies:
    36
    Views:
    1,393
    Chris Fogelklou
    Apr 20, 2004
  5. Pavel
    Replies:
    7
    Views:
    539
    Pavel
    Sep 19, 2010
Loading...

Share This Page