0

Is it possible to do something like this on the C language:

class A
{
    public:
        int x;
        int y;
};
class B : public A
{
    public:
        int w;
        int h;
};

void func(A a)
{
    //Do something here
}

int main()
{
    B b;
    func(b);

    return 0;
}

in C with structures? And how should I implement it?

Deanie
  • 2,316
  • 2
  • 19
  • 35
Erik W
  • 2,590
  • 4
  • 20
  • 33
  • 2
    Related http://stackoverflow.com/questions/351733/can-you-write-object-oriented-code-in-c – R Sahu Apr 07 '15 at 15:36
  • 1
    Probably you can `union` `A` with `A` plus a nameless `struct` of `w` and `h`, so that you can create `B` by appending to the end of `a` – user3528438 Apr 07 '15 at 15:58

2 Answers2

2

Short answer: no.

Longer answer: C is not object oriented, and it will never be object oriented. You can do many object oriented things, like creating structs, and functions that operate on structs. But if you try to write all your C code by attempting to emulate object oriented standards, you will find it brutal and inefficient. Inheritance is one of those things that will be brutal and inefficient to implement.

However, people frequently use composition instead of inheritance. This is where you include class A in class B, instead of inheriting. If you decide on including parent structs as the first member, you could do this:

struct A { /* stuff */ };
struct B {
  struct A a;
  /* more stuff */
}
void func(void *obj) {
  struct A *a = (struct A *)obj;
  /* do stuff */
}
int main(int argc, char **argv) {
  struct B b;
  func(&b);
}

This is a little scary, and there's no type checking. It will work in many situations, but it won't necessarily have things like polymorphism that you expect from object oriented languages. Long story short is, try not to rely on object oriented practices -- OOP is just one paradigm, and it's not the only one out there!

brenns10
  • 3,109
  • 3
  • 22
  • 24
1

Yes, it is possible with struct in C the same way as in C++, i.e., by passing objects to the functions. Suppose the struct is:

struct A {
           int a;
           int b;
         };

And the function is:

void func(A a)
{
//Do something here
}

Then the main() function will be:

int main()
{
struct A b;
func(b);

return 0;
}

Inheritance is not possible in C. If your aim is to have two structures, one deriving contents from the other, then this may help:

struct A {
           int a;
           int b;
         };

struct B {
           int x;
           int y;
           struct A ob_a;
         };

The function can be modified as:

void func(B b)
{
//Do something here
}

You can call the function as:

struct B ob_b;
func(ob_b);
Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43