1

I want to implement methods in C language. I know C language doesn't support Object Oriented Programming. But is there a way to do it? Or is it can't be done? Because it need to done by C.

struct student
{
    int name;
    int address;

    void speak() 
    {
        /* code */
    }

};

int main()
{

    //code ..

    student.speak();

}

This is how my code look like.

Chamin Wickramarathna
  • 1,672
  • 2
  • 20
  • 34

2 Answers2

6

You may partially emulate this by using pointer to function.

struct student
{
    int name;
    int address;

    void (*speak)();
};

void speak_func() {/*...*/}

int main()
{
  //code ..
  struct student student;
  student.speak = speak_func;

  student.speak();
}
alk
  • 69,737
  • 10
  • 105
  • 255
Matt
  • 13,674
  • 1
  • 18
  • 27
2

No, that's not possible. You can do some tricks to get a result that looks similar but I don't recommend them. In C, you would just use a function:

void speak(struct student *student) {
    /* ... */
}
fuz
  • 88,405
  • 25
  • 200
  • 352
  • Your answer is incorrect. Google for "oop in C" where you'll even find a pdf on the subject. I've done this for years myself. – Rob Oct 01 '15 at 19:21
  • @Rob Where exactly is my answer wrong? – fuz Oct 02 '15 at 15:42