0

I know that one of the major advantages of C++ as a programming languages is the fact that It can support OOP.

Example:

#include <iostream>
using namespace std;

class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area () {return (x*y);}
};

void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

int main () {
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}

I was wondering if C also supported OOP and if so how it was done.

user1922878
  • 2,833
  • 3
  • 13
  • 7

1 Answers1

2

Generally, you just use structs and pass a context pointer around. Direct conversion of your example:

#include <stdio.h>

struct rectangle {
    int x, y;
};

void rectangle_set_values (struct rectangle * rectangle, int a, int b) {
  rectangle->x = a;
  rectangle->y = b;
}

int rectangle_area (struct rectangle * rectangle) {
  return rectangle->x * rectangle->y;
}

int main () {
  struct rectangle rect;
  rectangle_set_values(&rect, 3, 4);
  printf("area: %d", rectangle_area(&rect));
  return 0;
}
James M
  • 18,506
  • 3
  • 48
  • 56