SlideShare a Scribd company logo
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
○

More Related Content

What's hot (20)

Php string function
Php string function Php string function
Php string function
Ravi Bhadauria
 
Inheritance
InheritanceInheritance
Inheritance
Srinath Dhayalamoorthy
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
Manish Bothra
 
OOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOPOOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOP
Mudasir Qazi
 
Tomcat
TomcatTomcat
Tomcat
Venkat Pinagadi
 
PHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web DevelopmentPHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web Development
Edureka!
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
Dror Helper
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
Confiz
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
Raghuveer Guthikonda
 
Web design - Applications and web application definition
Web design - Applications and web application definitionWeb design - Applications and web application definition
Web design - Applications and web application definition
Mustafa Kamel Mohammadi
 
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)
Minh Dao
 
Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners
Vibhawa Nirmal
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
Madhuri Kavade
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
Avanade Nederland
 
JNDI
JNDIJNDI
JNDI
Shobana Pattabiraman
 
Visual Studio IDE
Visual Studio IDEVisual Studio IDE
Visual Studio IDE
Sayantan Sur
 
Introduction to Web Services
Introduction to Web ServicesIntroduction to Web Services
Introduction to Web Services
Thanachart Numnonda
 
Flask
FlaskFlask
Flask
Mamta Kumari
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
12. oracle database architecture
12. oracle database architecture12. oracle database architecture
12. oracle database architecture
Amrit Kaur
 
OOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOPOOP - Benefits and advantages of OOP
OOP - Benefits and advantages of OOP
Mudasir Qazi
 
PHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web DevelopmentPHP and MySQL : Server Side Scripting For Web Development
PHP and MySQL : Server Side Scripting For Web Development
Edureka!
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
Dror Helper
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
Confiz
 
Web design - Applications and web application definition
Web design - Applications and web application definitionWeb design - Applications and web application definition
Web design - Applications and web application definition
Mustafa Kamel Mohammadi
 
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)
Cloud Firestore – From JSON Deserialization to Object Document Mapping (ODM)
Minh Dao
 
Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners
Vibhawa Nirmal
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
Madhuri Kavade
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
Avanade Nederland
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
12. oracle database architecture
12. oracle database architecture12. oracle database architecture
12. oracle database architecture
Amrit Kaur
 

Similar to OO-like C Programming: Struct Inheritance and Virtual Function (20)

Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
sagaroceanic11
 
22 scheme OOPs with C++ BCS306B_module4.pdf
22 scheme  OOPs with C++ BCS306B_module4.pdf22 scheme  OOPs with C++ BCS306B_module4.pdf
22 scheme OOPs with C++ BCS306B_module4.pdf
sindhus795217
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
nisarmca
 
virtual
virtualvirtual
virtual
SangeethaSasi1
 
B.sc CSIT 2nd semester C++ Unit6
B.sc CSIT  2nd semester C++ Unit6B.sc CSIT  2nd semester C++ Unit6
B.sc CSIT 2nd semester C++ Unit6
Tekendra Nath Yogi
 
Virtual Function
Virtual FunctionVirtual Function
Virtual Function
Lovely Professional University
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptx
rayanbabur
 
Example for Virtual and Pure Virtual function.pdf
Example for Virtual and Pure Virtual function.pdfExample for Virtual and Pure Virtual function.pdf
Example for Virtual and Pure Virtual function.pdf
rajaratna4
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
KevinNicolaNatanael
 
polymorphism for b.tech iii year students
polymorphism for b.tech iii year studentspolymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
 
Virtual function
Virtual functionVirtual function
Virtual function
zindadili
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented Programming
Gamindu Udayanga
 
6. Virtual base class.pptx and virtual function
6. Virtual base class.pptx and virtual function6. Virtual base class.pptx and virtual function
6. Virtual base class.pptx and virtual function
archana22486y
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
ismartshanker1
 
Wade Not in Unknown Waters. Part Four.
Wade Not in Unknown Waters. Part Four.Wade Not in Unknown Waters. Part Four.
Wade Not in Unknown Waters. Part Four.
PVS-Studio
 
C++ Multiple Inheritance
C++ Multiple InheritanceC++ Multiple Inheritance
C++ Multiple Inheritance
harshaltambe
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4Object Oriented Programming (OOP) using C++ - Lecture 4
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Chapter10_Data_Abstraction_and_Object_Orientation_4e.ppt
Chapter10_Data_Abstraction_and_Object_Orientation_4e.pptChapter10_Data_Abstraction_and_Object_Orientation_4e.ppt
Chapter10_Data_Abstraction_and_Object_Orientation_4e.ppt
techtrainer11
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
LogeekNightUkraine
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptxObject Oriented Programming using C++: Ch11 Virtual Functions.pptx
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
22 scheme OOPs with C++ BCS306B_module4.pdf
22 scheme  OOPs with C++ BCS306B_module4.pdf22 scheme  OOPs with C++ BCS306B_module4.pdf
22 scheme OOPs with C++ BCS306B_module4.pdf
sindhus795217
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
nisarmca
 
B.sc CSIT 2nd semester C++ Unit6
B.sc CSIT  2nd semester C++ Unit6B.sc CSIT  2nd semester C++ Unit6
B.sc CSIT 2nd semester C++ Unit6
Tekendra Nath Yogi
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptx
rayanbabur
 
Example for Virtual and Pure Virtual function.pdf
Example for Virtual and Pure Virtual function.pdfExample for Virtual and Pure Virtual function.pdf
Example for Virtual and Pure Virtual function.pdf
rajaratna4
 
polymorphism for b.tech iii year students
polymorphism for b.tech iii year studentspolymorphism for b.tech iii year students
polymorphism for b.tech iii year students
Somesh Kumar
 
Virtual function
Virtual functionVirtual function
Virtual function
zindadili
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented Programming
Gamindu Udayanga
 
6. Virtual base class.pptx and virtual function
6. Virtual base class.pptx and virtual function6. Virtual base class.pptx and virtual function
6. Virtual base class.pptx and virtual function
archana22486y
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
ismartshanker1
 
Wade Not in Unknown Waters. Part Four.
Wade Not in Unknown Waters. Part Four.Wade Not in Unknown Waters. Part Four.
Wade Not in Unknown Waters. Part Four.
PVS-Studio
 
C++ Multiple Inheritance
C++ Multiple InheritanceC++ Multiple Inheritance
C++ Multiple Inheritance
harshaltambe
 
Chapter10_Data_Abstraction_and_Object_Orientation_4e.ppt
Chapter10_Data_Abstraction_and_Object_Orientation_4e.pptChapter10_Data_Abstraction_and_Object_Orientation_4e.ppt
Chapter10_Data_Abstraction_and_Object_Orientation_4e.ppt
techtrainer11
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
LogeekNightUkraine
 
Ad

Recently uploaded (20)

dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Integrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FMEIntegrating Survey123 and R&H Data Using FME
Integrating Survey123 and R&H Data Using FME
Safe Software
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Ad

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 ○