User:Ujoimro/object oriented programming in c
Though not enforced, object oriented programming is possible in C. The main constraints added by C++ can be accepted as a convention in the source code. The object oriented programming paradigm is widely used in C projects including the Linux kernel and SQLite.
Basic Concepts
Classes
Classes are composed from two major entity types: data and methods. There is already a tool in C to create structured data types: struct. Simple classes can be translated directly in C:
class person:
name height age
can be translated as
struct person {
char*name; int height; int age;
}
The methods can be declared as functions, whereas the pointer to the data of the class is put -- by convention -- as first parameter:
class person:
name
height
age
def set_age(self, n):
self.age=n
could be translated as
struct person {
char*name; int height; int age;
}
void set_age(person * self, int age) {
self->age=age;
}
methods can also be directly included in the structures
struct person {
char*name; int height; int age; void (*set_age)(struct person*, int);
}
This allows virtual methods, as the method can be set during the allocation:
void set_age_v1(person * self, int age) {
self->age=age+1;
}
void set_age_v2(person * self, int age) {
self->age=age+2;
}
struct person p1; p1->set_age=&set_age_v1;
p1->set_age(p1, 10);
Content Disclaimer
Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.
- The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
- There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
- It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
- Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
- Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.