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)

PPTX
Namespace in C++ Programming Language
Himanshu Choudhary
 
PPTX
Abstract class in c++
Sujan Mia
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PDF
Let us c chapter 4 solution
rohit kumar
 
PPTX
Principles and advantages of oop ppt
daxesh chauhan
 
PPTX
Function in c program
umesh patil
 
PPTX
Dynamic Memory Allocation(DMA)
Kamal Acharya
 
PPTX
User defined functions in C
Harendra Singh
 
PPT
Variables in C Programming
programming9
 
PDF
Chapter 1 : Balagurusamy_ Programming ANsI in C
BUBT
 
PPTX
Tokens in C++
Mahender Boda
 
PDF
Unit ii chapter 2 Decision making and Branching in C
Sowmya Jyothi
 
PPTX
Increment and Decrement operators in C++
Neeru Mittal
 
TXT
c++ program for Railway reservation
Swarup Kumar Boro
 
PPTX
Storage classes in C
Nitesh Bichwani
 
PDF
Domain Modeling with FP (DDD Europe 2020)
Scott Wlaschin
 
PDF
Access specifiers (Public Private Protected) C++
vivekkumar2938
 
PDF
Introduction to oops concepts
Nilesh Dalvi
 
PPTX
Overloading of io stream operators
SARAVANAN GOPALAKRISHNAN
 
PDF
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Sowmya Jyothi
 
Namespace in C++ Programming Language
Himanshu Choudhary
 
Abstract class in c++
Sujan Mia
 
Functions in c++
Rokonuzzaman Rony
 
Let us c chapter 4 solution
rohit kumar
 
Principles and advantages of oop ppt
daxesh chauhan
 
Function in c program
umesh patil
 
Dynamic Memory Allocation(DMA)
Kamal Acharya
 
User defined functions in C
Harendra Singh
 
Variables in C Programming
programming9
 
Chapter 1 : Balagurusamy_ Programming ANsI in C
BUBT
 
Tokens in C++
Mahender Boda
 
Unit ii chapter 2 Decision making and Branching in C
Sowmya Jyothi
 
Increment and Decrement operators in C++
Neeru Mittal
 
c++ program for Railway reservation
Swarup Kumar Boro
 
Storage classes in C
Nitesh Bichwani
 
Domain Modeling with FP (DDD Europe 2020)
Scott Wlaschin
 
Access specifiers (Public Private Protected) C++
vivekkumar2938
 
Introduction to oops concepts
Nilesh Dalvi
 
Overloading of io stream operators
SARAVANAN GOPALAKRISHNAN
 
Arrays in c unit iii chapter 1 mrs.sowmya jyothi
Sowmya Jyothi
 

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

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

Recently uploaded (20)

PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
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 ○