OOP_C[0] = “Polymorphism”

We can say that polymorphism means having many forms. I can hear you say, “C language is not an OOP language”. Yes you are right, but there is a very fine line in this answer;

Answer can be yes or no, depending on:

if you ask “is C an object oriented language?”, the answer is “no” because it do not have object oriented constructors, keywords, semantic etc…

if you intend “can I realize OOP in C?”, the answer is yes, because OOP is not only a requirement of a language, but also a way of “thinking”, an approach to programming, before to touch some language or another. However the implementation of OOP in C (or any other language not natively designed to be OOP) will be surely “forced” and much hard to manage then any other OOP language, so also some limitation shall be expected.

There are some techniques in this subject.

taken from geeksforgeeks

Today, we will try to implement the structure at run time with virtual functions.(Dynamic or late binding)

#include "stdio.h"
#include "stdbool.h"

struct which_series
    const struct vtable* vptrinc;
    const char* name;    

struct vtable
    void (*is_watched)(struct which_series* self);

static void is_watched(struct which_series* self)
    printf("\r\n Yes, %s watched ", self -> name);

void is_watched_for_client(struct which_series* self)
    const struct vtable* vptr = *(&self -> vptrinc);
    if (vptr -> is_watched != NULL)
        vptr -> is_watched(self);

        printf("\r\n No, %s not watched yet ", self -> name);

int main()
    struct vtable spycraft = { &is_watched };
    struct which_series spycraft_series  = { &spycraft, "Spycraft" };

    struct vtable lupin = { (void*)0 };
    struct which_series lupin_series = { &lupin, "Lupin" };


How it is works ?

NOTE: The alignment of the Rectangle structure and the inherited attributes from the Shape
structure is guaranteed by the C Standard WG14/N1124. Section of this Standard, says:
“… A pointer to a structure object, suitably converted, points to its initial member. There may be
unnamed padding within a structure object, but not at its beginning”.

Again, since “vptrinc” is the first member in the “which_series” structure it actually has the same address as the instance self.

printf("\r\n Addr in the structure < %x > ", self -> vptrinc);
printf("\r\n spycraft addr < %x > ", &spycraft);
//gives same address

Bir Cevap Yazın

Please log in using one of these methods to post your comment:

WordPress.com Logosu

WordPress.com hesabınızı kullanarak yorum yapıyorsunuz. Çıkış  Yap /  Değiştir )

Google fotoğrafı

Google hesabınızı kullanarak yorum yapıyorsunuz. Çıkış  Yap /  Değiştir )

Twitter resmi

Twitter hesabınızı kullanarak yorum yapıyorsunuz. Çıkış  Yap /  Değiştir )

Facebook fotoğrafı

Facebook hesabınızı kullanarak yorum yapıyorsunuz. Çıkış  Yap /  Değiştir )

Connecting to %s