-1

I came across this code, and I was interested what the constructs marked below by comments //<-- This are.

If it has a name then I would like to know (to google it and get more info if possible).

#include <stdio.h>
typedef struct point {
 float x,y;
 void print(void);
} dot;

typedef struct rect {
  dot pt1,pt2;
  float area(void);
  dot center(void);
  void print(void);
} rectangle;

void dot::print(void){ //<-- This
  printf("(%3.1f,%3.1f)", x, y);
}

void rectangle::print(void){ //<-- This
  pt1.print(); printf(":"); pt2.print(); 
}

dot rectangle::center(void){ //<-- This 
  dot c; c.x=(pt1.x + pt2.x)/2;
  c.y=(pt1.y + pt2.y)/2; return c;
}

float rectangle::area(void){ //<-- This
  return((pt2.x-pt1.x)*(pt2.y-pt1.y)); 
}
Keith Thompson
  • 242,098
  • 41
  • 402
  • 602

2 Answers2

2

They are implementations of the functions defined in the classes (structs) abouse. Usually though, you would do this in your cpp file, so you would have your h file with:

class Foo{
     int method1();
     int method2();
}

and then in your cpp file you would add the implementation using:

int Foo::method1(){
   ....
}

This code is a bit silly though, because the classes are defined in ye olde c way using the typedef struct syntax. This would make sense in some cases, because c code is also valid c++ so you could have code that compiled as both. However c++ is not always valid c and this code id definitely c++ because of the member functions, so there is no point in using the typedef struct syntax. It is probably old code that has been modified.

David van rijn
  • 1,916
  • 8
  • 21
0

The lines you are pointing to refer to the declaration of a function. I will explain one of these lnes, because you can apply the same lgic to the rest of them.

Let's look at the line:

    void dot::print(void){

The first word in this line, void, defines the type of data returned fromthe function. Since it is void, no value is returned from this function, which is evident fomthe fact that there is no return statement in the entire function.

    void dot::print(void) {
        printf("(%3.1f,%3.1f)", x, y); // this is the last line of the function. This function does not pass on any value or data
    }

Next is dot::, which is an object of struct point. If you see after the closing } of the struct point, you wil see that dot is declared here.

For the object dot, there is a function declaration called print(). This function is defined here, but since we have to indicate that we have to indicate that print() is a member of dot, we add the dot:: before the print(void) in the declaration.

Lastly is the void in parenthesis. This simply means that the function has no input parameters from the function that has called it; in other words, it does not need any data from outside the function.


Just as a recommendation, your code is more c than c++. You would be better off tagging this question as c instead of c++.

BusyProgrammer
  • 2,693
  • 5
  • 17
  • 31