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,334
  • 1
  • 17
  • 32

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
  • 68,300
  • 10
  • 92
  • 234
Matt
  • 12,100
  • 1
  • 13
  • 21
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
  • 82,933
  • 24
  • 182
  • 332
  • 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