2 Replies Latest reply on Nov 21, 2011 4:56 PM by Steve.Clamage-Oracle

    help c++

      hi all

      how can we write this in c++?

      #include <stdio.h>
      #include <stdlib.h>
      typedef struct {
      int x, y;
      } * Point;

      void init (Point p) {p->x = 0; p->y = 0;}
      void set (Point p, int a, int b) {p->x = a; p->y = b;}
      void showw (Point p) {printf("%d %d\n", p->x, p->y);}
      Point p = (Point) malloc(8),
      q = (Point) malloc(8);
      set(q, 1, 2);
      printf("%d %d\n", q->x, q->y);

      thanks in advance
        • 1. Re: help c++

          You really need to buy a book (or several) or have a training course.

          If you want to have a kind on "canonical C++" point class, then I'd

          1. Use <iostream> / cout and not the C <stdio.h> / printf
          2. Define a class not a struct. No typedef for the class name.
          3. Replace the init function with a constructor.
          4. Replace with set function with constructors and/or operator=
          5. Replace the showw with an operator<<
          6. Use new, not malloc. Use delete (you example doesn't use free, it leaks)
          7. main() should be defined to return int.

          • 2. Re: help c++
            Let me add to Paul's reply.
            Since C++ is approximately a superset of C, well-written C programs are also C++ programs, except for a few mostly simple differences.
            In your example, both C and C++ require a return type of int for function main, although some C compilers don't enforce that rule. With that change, your program is syntactically valid as a C++ program. (As either a C or C++ program, it has some other problems.)

            For another example, the traditional first C program
            #include <stdio.h>
            int main()
                printf("Hello, world!\n");
                return 0;
            Is a perfectly valid C++ program.

            So when you ask how to turn a C program into a C++ program, there are two issues:
            1. Correcting code that is valid in C but not valid in C++.
            2. Deciding whether you want to use higher-level C++ programming techniques to replace lower-level C programming techniques. Paul's comments about using "new" instead of "malloc", and to use constructors for struct Point are good examples.