1. The encapsulation

C doesn’t have classes, but it does have structs and Pointers. We can simulate class behavior by storing data and function Pointers in a struct.

typedef struct _Parent
{
    int a;
    int b;
    void (*print)(struct _Parent *This);

}Parent;
Copy the code

The meaning of encapsulation is that functions and data are tied together, and data and data are tied together. This way, we can access all the data and traverse all the functions through a simple structure pointer. Encapsulation, which is a property of classes, and of course a property of data structures.

2. The inheritance

If you want to implement inheritance completely in C, it can be a bit difficult. But if you just do that, make sure that the subclass contains all the members of the parent class. It’s not hard.

typedef struct _Child
{  
    Parent parent;  
    int c;  
}Child;  
Copy the code

When designing C inheritance, all we need to do is put the underlying data at the top of the inherited structure. In this way, no matter the data access, data strong transfer, data access will not have any problems.

3. The polymorphism

This feature is perhaps the most useful in object-oriented thinking. Implementing this feature in C takes a little trickery, but it’s not impossible. We use the two structures defined above: Parent, Child. A simple example of polymorphism is described.

#include <stdio.h> #include <stdlib.h> typedef struct _Parent { int a; int b; void (*print)(struct _Parent *This); }Parent; typedef struct _Child { Parent parent; int c; }Child; void print_parent(Parent *This) { printf("a = %d. b = %d.\n", This->a, This->b); } void print_child(Parent *This) { Child *p = (Child *)This; printf("a = %d. b = %d. c = %d.\n", p->parent.a, p->parent.b, p->c); } Parent *create_parent(int a, int b) { Parent *This; This = NULL; This = (Parent *)malloc(sizeof(Parent)); if (This ! = NULL) { This->a = a; This->b = b; This->print = print_parent; printf("Create parent successfully! \n"); } return This; } void destroy_parent(Parent **p) { if (*p ! = NULL) { free(*p); *p = NULL; printf("Delete parent successfully! \n"); } } Child *create_child(int a, int b, int c) { Child *This; This = NULL; This = (Child *)malloc(sizeof(Child)); if (This ! = NULL) { This->parent.a = a; This->parent.b = b; This->c = c; This->parent.print = print_child; printf("Create child successfully! \n"); } return This; } void destroy_child(Child **p) { if (*p ! = NULL) { free(*p); *p = NULL; printf("Delete child successfully! \n"); } } int main() { Child *p = create_child(1, 2, 3); Parent *q; q = (Parent *)p; q->print(q); destroy_child(&p); system("pause"); return 0; }Copy the code