SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
OO-Like C:
Struct Inheritance and Virtual
Functions
Yosen Chen
Outline
● Implement the following Object-Oriented techniques in
Pure C:
○ Struct “inheritance”
○ Member functions using member variables/functions
○ “Virtual” functions
● PS:
○ I’m not going to condemn non-OO like C, but provide more
programming techniques in C. We may base on the task situations to
consider its fitness.
Struct Inheritance
Class Inheritance in C++ and C (1/2)
This is how we do class inheritance in C++:
// A and B are derived from Base
class Base
{
public:
int type;
int op_Base(int i);
};
class A : public Base
{
public:
int* dataA;
int op_A(int i);
};
class B : public Base
{
public:
int* dataB;
int op_B(int i);
};
This is how we do struct “inheritance” in C:
struct Base
{
int type;
int (*op_Base) (struct Base* _this, int i);
};
struct A
{
struct Base _base; // inherit from Base
int* dataA;
int (*op_A) (struct A* _this, int i);
};
struct B
{
struct Base _base; //inherit from Base
int* dataB;
int (*op_B) (struct B* _this, int i);
};
PS: I would tell you why we need _this later
Class Inheritance in C++ and C (1/2)
In C++, for derived class A, we can access
members of both Base and A:
Given we have:
A a;
Then we can use:
a.dataA
a.op_A(5);
a.type
a.op_Base(5);
We can do the same thing in C as we do in
C++:
Given we have:
struct A a;
Then we can use:
a.dataA
a.op_A(&a, 5);
and
a._base.type
a._base.op_Base(&a._base, 5);
or, more elegantly
struct Base* pBase = (struct Base*)&a;
pBase->type
pBase->op_Base(pBase, 5);
PS: in this way, struct A users can access Base
members as they are struct Base users.
Memory Allocation of Struct “Inheritance”
AddrOffset 0~3: type
AddrOffset 4~7: op_Base
AddrOffset 8~11: dataA
AddrOffset 12~15: op_A
...
start address of a
(i.e., &a)
if we declare struct A a;
The memory allocation of a is like:
a._base
a
Remark:
start address of a == &a == &a._base == &a._base.type
a._base.type == ((struct Base*)&a)->type //this concept can be used in virtual
Member Functions Using Other
Members
Member Function Using Other Class
Members (C++ vs. C)
In C++, member functions can access other
class members (functions, variables):
For example, we can define function op_A as
below:
int A::op_A(int i)
{
return op_Base(i) + type + dataA[i];
}
We can do the same thing in C as we do in C++:
(using _this)
int A_op_A(struct A* _this, int i)
{
return _this->_base.op_Base(&_this->_base, i)
+ _this->_base.type
+ _this->dataA[i];
}
For struct construction, we have:
void A_ctor(struct A* _this)
{
Base_ctor(&_this->_base); // call Base ctor
_this->op_A = A_op_A;
...
}
For A’s user, we call:
a.op_A(&a, 5);
Virtual Function
Virtual Functions in C++
Why we need virtual?
● What is virtual function?
○ By Wikipedia’s definition: In object-oriented programming, a virtual function
or virtual method is a function or method whose behavior can be overridden
within an inheriting class by a function with the same signature. This concept is
an important part of the polymorphism portion of object-oriented programming
(OOP)
● Advantages: (better software architecture design)
1. base class users can use derived classes without modifying their
code.
2. we can localize the knowledge of which derived class is being used.
Virtual Functions in C++
In C++, virtual function goes like this:
class Interface {
...
virtual bool execute();
}
class ImpA : public Interface {
…
virtual bool execute();
}
class ImpADerived : public ImpA {
...
virtual bool execute();
}
For general class Interface users:
void func(Interface* pInterf) { pInterf->execute(); }
ImpADerived a; func(&a);
PS: actually, ImpADerived::execute() is called, instead of Interface::execute()
PS: Inside func(), it doesn’t need to know which version of execute() is being
used.
Class Userhold
Actually,ituses...
“Virtual” Functions in Pure C (1/2)
In C, virtual functions can be achieved via pointer manipulation:
struct Interface {
...
BOOL (*execute) (struct Interface* _this);
}
struct ImpA {
struct Interface _base; //derived from Interface
...
}
struct ImpADerived {
struct ImpA _base; //derived from ImpA
…
}
in ImpADerived constructor:
void ImpADerived_ctor (struct ImpADerived* _this) {
_this->_base->_base.execute = ImpADerived_execute;
…
}
continued in the next page
Class Userhold
Actually,ituse...
“Virtual” Functions in Pure C (2/2)
In C, virtual functions can be achieved via pointer manipulation:
The following is how we implement ImpADerived’s execute():
BOOL ImpADerived_execute (struct Interface* _this) {
// here we can check _this->mType to confirm struct version first
struct ImpADerived* _this2 = (struct ImpADerived*)_this;
_this2->doMoreThings(_this2);
…
}
So just like what we did in C++ virtual, for general Interface users:
void func(struct Interface* pInterf) { pInterf->execute(pInterf); }
struct ImpADerived a;
ImpADerived_ctor(&a);
func((struct Interface*)&a);
Inside func(), ImpADerived::execute() is used instead of Interface::execute()
Now we achieve the same functionality in C as in C++
Class Userhold
Actually,ituses...
Reference & Appendix
● Appendix:
○ Sample code on GitHub:
https://github.com/YosenChen/SoftwareArchitecture
Design/tree/master/OOLikeC-2
○

Mais conteúdo relacionado

Mais procurados

Docker Swarm for Beginner
Docker Swarm for BeginnerDocker Swarm for Beginner
Docker Swarm for BeginnerShahzad Masud
 
Dart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDSCVSSUT
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languagetanmaymodi4
 
Infrastructure Deployment with Docker & Ansible
Infrastructure Deployment with Docker & AnsibleInfrastructure Deployment with Docker & Ansible
Infrastructure Deployment with Docker & AnsibleRobert Reiz
 
Event Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfEvent Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfAliEndris3
 
Advanced Namespaces and cgroups
Advanced Namespaces and cgroupsAdvanced Namespaces and cgroups
Advanced Namespaces and cgroupsKernel TLV
 
Prerequisite knowledge for shared memory concurrency
Prerequisite knowledge for shared memory concurrencyPrerequisite knowledge for shared memory concurrency
Prerequisite knowledge for shared memory concurrencyViller Hsiao
 
Building Your Own DSL with Xtext
Building Your Own DSL with XtextBuilding Your Own DSL with Xtext
Building Your Own DSL with XtextGlobalLogic Ukraine
 
Scientific calcultor-Java
Scientific calcultor-JavaScientific calcultor-Java
Scientific calcultor-JavaShaibal Ahmed
 
Linux Kernel Crashdump
Linux Kernel CrashdumpLinux Kernel Crashdump
Linux Kernel CrashdumpMarian Marinov
 
Introduction to gdb
Introduction to gdbIntroduction to gdb
Introduction to gdbOwen Hsu
 
Inside Android's UI
Inside Android's UIInside Android's UI
Inside Android's UIOpersys inc.
 

Mais procurados (20)

C fundamental
C fundamentalC fundamental
C fundamental
 
Shell programming
Shell programmingShell programming
Shell programming
 
Docker Swarm for Beginner
Docker Swarm for BeginnerDocker Swarm for Beginner
Docker Swarm for Beginner
 
Dart and Flutter Basics.pptx
Dart and Flutter Basics.pptxDart and Flutter Basics.pptx
Dart and Flutter Basics.pptx
 
Swift Introduction
Swift IntroductionSwift Introduction
Swift Introduction
 
Introduction to Data Oriented Design
Introduction to Data Oriented DesignIntroduction to Data Oriented Design
Introduction to Data Oriented Design
 
tmux
tmuxtmux
tmux
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Infrastructure Deployment with Docker & Ansible
Infrastructure Deployment with Docker & AnsibleInfrastructure Deployment with Docker & Ansible
Infrastructure Deployment with Docker & Ansible
 
Event Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfEvent Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdf
 
Advanced Namespaces and cgroups
Advanced Namespaces and cgroupsAdvanced Namespaces and cgroups
Advanced Namespaces and cgroups
 
Prerequisite knowledge for shared memory concurrency
Prerequisite knowledge for shared memory concurrencyPrerequisite knowledge for shared memory concurrency
Prerequisite knowledge for shared memory concurrency
 
Building Your Own DSL with Xtext
Building Your Own DSL with XtextBuilding Your Own DSL with Xtext
Building Your Own DSL with Xtext
 
Scientific calcultor-Java
Scientific calcultor-JavaScientific calcultor-Java
Scientific calcultor-Java
 
Linux Kernel Crashdump
Linux Kernel CrashdumpLinux Kernel Crashdump
Linux Kernel Crashdump
 
Function in c
Function in cFunction in c
Function in c
 
Introduction to gdb
Introduction to gdbIntroduction to gdb
Introduction to gdb
 
Introduction to Linux Drivers
Introduction to Linux DriversIntroduction to Linux Drivers
Introduction to Linux Drivers
 
Embedded Android : System Development - Part IV
Embedded Android : System Development - Part IVEmbedded Android : System Development - Part IV
Embedded Android : System Development - Part IV
 
Inside Android's UI
Inside Android's UIInside Android's UI
Inside Android's UI
 

Semelhante a OO-like C Programming: Struct Inheritance and Virtual Function

Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Abu Saleh
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of cTushar B Kute
 
Dotnet unit 4
Dotnet unit 4Dotnet unit 4
Dotnet unit 4007laksh
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphismFALLEE31188
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++Swarup Boro
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++Swarup Kumar Boro
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classDeepak Singh
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptishan743441
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 

Semelhante a OO-like C Programming: Struct Inheritance and Virtual Function (20)

Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Lecture5
Lecture5Lecture5
Lecture5
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Dotnet unit 4
Dotnet unit 4Dotnet unit 4
Dotnet unit 4
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
Overloading
OverloadingOverloading
Overloading
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
C++ language
C++ languageC++ language
C++ language
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
Interfaces c#
Interfaces c#Interfaces c#
Interfaces c#
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 

Último

Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 

Último (20)

Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

OO-like C Programming: Struct Inheritance and Virtual Function

  • 1. OO-Like C: Struct Inheritance and Virtual Functions Yosen Chen
  • 2. Outline ● Implement the following Object-Oriented techniques in Pure C: ○ Struct “inheritance” ○ Member functions using member variables/functions ○ “Virtual” functions ● PS: ○ I’m not going to condemn non-OO like C, but provide more programming techniques in C. We may base on the task situations to consider its fitness.
  • 4. Class Inheritance in C++ and C (1/2) This is how we do class inheritance in C++: // A and B are derived from Base class Base { public: int type; int op_Base(int i); }; class A : public Base { public: int* dataA; int op_A(int i); }; class B : public Base { public: int* dataB; int op_B(int i); }; This is how we do struct “inheritance” in C: struct Base { int type; int (*op_Base) (struct Base* _this, int i); }; struct A { struct Base _base; // inherit from Base int* dataA; int (*op_A) (struct A* _this, int i); }; struct B { struct Base _base; //inherit from Base int* dataB; int (*op_B) (struct B* _this, int i); }; PS: I would tell you why we need _this later
  • 5. Class Inheritance in C++ and C (1/2) In C++, for derived class A, we can access members of both Base and A: Given we have: A a; Then we can use: a.dataA a.op_A(5); a.type a.op_Base(5); We can do the same thing in C as we do in C++: Given we have: struct A a; Then we can use: a.dataA a.op_A(&a, 5); and a._base.type a._base.op_Base(&a._base, 5); or, more elegantly struct Base* pBase = (struct Base*)&a; pBase->type pBase->op_Base(pBase, 5); PS: in this way, struct A users can access Base members as they are struct Base users.
  • 6. Memory Allocation of Struct “Inheritance” AddrOffset 0~3: type AddrOffset 4~7: op_Base AddrOffset 8~11: dataA AddrOffset 12~15: op_A ... start address of a (i.e., &a) if we declare struct A a; The memory allocation of a is like: a._base a Remark: start address of a == &a == &a._base == &a._base.type a._base.type == ((struct Base*)&a)->type //this concept can be used in virtual
  • 7. Member Functions Using Other Members
  • 8. Member Function Using Other Class Members (C++ vs. C) In C++, member functions can access other class members (functions, variables): For example, we can define function op_A as below: int A::op_A(int i) { return op_Base(i) + type + dataA[i]; } We can do the same thing in C as we do in C++: (using _this) int A_op_A(struct A* _this, int i) { return _this->_base.op_Base(&_this->_base, i) + _this->_base.type + _this->dataA[i]; } For struct construction, we have: void A_ctor(struct A* _this) { Base_ctor(&_this->_base); // call Base ctor _this->op_A = A_op_A; ... } For A’s user, we call: a.op_A(&a, 5);
  • 10. Virtual Functions in C++ Why we need virtual? ● What is virtual function? ○ By Wikipedia’s definition: In object-oriented programming, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature. This concept is an important part of the polymorphism portion of object-oriented programming (OOP) ● Advantages: (better software architecture design) 1. base class users can use derived classes without modifying their code. 2. we can localize the knowledge of which derived class is being used.
  • 11. Virtual Functions in C++ In C++, virtual function goes like this: class Interface { ... virtual bool execute(); } class ImpA : public Interface { … virtual bool execute(); } class ImpADerived : public ImpA { ... virtual bool execute(); } For general class Interface users: void func(Interface* pInterf) { pInterf->execute(); } ImpADerived a; func(&a); PS: actually, ImpADerived::execute() is called, instead of Interface::execute() PS: Inside func(), it doesn’t need to know which version of execute() is being used. Class Userhold Actually,ituses...
  • 12. “Virtual” Functions in Pure C (1/2) In C, virtual functions can be achieved via pointer manipulation: struct Interface { ... BOOL (*execute) (struct Interface* _this); } struct ImpA { struct Interface _base; //derived from Interface ... } struct ImpADerived { struct ImpA _base; //derived from ImpA … } in ImpADerived constructor: void ImpADerived_ctor (struct ImpADerived* _this) { _this->_base->_base.execute = ImpADerived_execute; … } continued in the next page Class Userhold Actually,ituse...
  • 13. “Virtual” Functions in Pure C (2/2) In C, virtual functions can be achieved via pointer manipulation: The following is how we implement ImpADerived’s execute(): BOOL ImpADerived_execute (struct Interface* _this) { // here we can check _this->mType to confirm struct version first struct ImpADerived* _this2 = (struct ImpADerived*)_this; _this2->doMoreThings(_this2); … } So just like what we did in C++ virtual, for general Interface users: void func(struct Interface* pInterf) { pInterf->execute(pInterf); } struct ImpADerived a; ImpADerived_ctor(&a); func((struct Interface*)&a); Inside func(), ImpADerived::execute() is used instead of Interface::execute() Now we achieve the same functionality in C as in C++ Class Userhold Actually,ituses...
  • 14. Reference & Appendix ● Appendix: ○ Sample code on GitHub: https://github.com/YosenChen/SoftwareArchitecture Design/tree/master/OOLikeC-2 ○