TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Learn to Implement C++ Class in C Programming
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Linux Tutorials

Learn to Implement C++ Class in C Programming

Last updated: Nov 05, 2023 8:13 pm
By Harsh S.
Share
6 Min Read
C++ Class Implementation class using C Programming Language
C++ Class Implementation class using C Programming Language
SHARE

In this post, we are going to tell you about the techniques for implementing a C++ class using C. But before we get on with the techniques,

Contents
Define C++ Class Constructors in CIntegrate C++ Class Encapsulation in your C ProgramIntroduce Polymorphism using Function Pointers

Design a C++ Class using C Language

let’s understand how close we can design a C structure to imitate a C++ class. The answer varies depending on the kind of object-oriented features you would like to have. Today, I’ll demonstrate adding three of the most commonly used object-oriented features to C structures.

Check out: 15 C Programming Tips and Tricks for Beginners

Define C++ Class Constructors in C

It’s the first step you need to execute for implementing a C++ class using C.

Constructors are exclusive functions that initialize an object of a class. In a similar pattern, we have to write a constructor-styled function that does the initialization for structure instances. Since the structure is a data type, you can’t directly assign values to it. You have to set values to instances or objects of such data types.

Let’s look into the code examples now.

1.1- In this example, we are providing the definition of a single argument constructor which initializes a structure called Object.

// Single argument Constructor to allocate memory
// and set default values
Object * Object_new(int index) {

    Object * obj = malloc(sizeof(Object));
    obj - > index = index;
    obj - > value = 0;
    return obj;
}

...

// Using constructor from your code
Object * O1 = Object_new(index++);
O1.value = 10;

In case you require multiple constructors for the Object structure, then you would need to decorate the function names. You can’t have more than one Object_new() function.

1.2- Follow the below example which allows an additional argument value and calls the single argument constructor function.

Object * Object_new_with_value(int index, int value) {
    Object * obj = Object_new(index);
    obj - > index = index;
    obj - > value = value;
    return obj;
}

Integrate C++ Class Encapsulation in your C Program

It’s another step toward implementing a C++ class using C. You easily do it by keeping the structure’s definitions in the source (.c) file instead of putting them in the header. And let the outer world access our objects through pointers, we only need to expose functions accepting such pointers as the “methods” of our objects.

Introduce Polymorphism using Function Pointers

Polymorphism in “C” can be implemented using function pointers. In other words, by introducing a compound structure that holds both the data and pointers to functions that manipulate the data. For example, let’s define a Database Adaptor class that connects a DB, selects a table, and executes a query without bothering about the type of DB being used. DB type should be allowed to switch dynamically.

// DB Api class exposing generic methods with the help of virtual pointers
typedef struct {
    int( * init)(void * sqlHandle);
    int( * connect)(void * sql, char * hostname, char * user, char * pwd, char * database);
    int( * close)(void * sql);
}
DBApi;

// DB class inheriting the DB Api class
typedef struct {
    DBApi api;
    void * handle;
}
DBClass;
DBClass db;

// DBClass object holding the MYSQL Api reference
db.api.init = & mysql_init;
db.api.connect = & mysql_real_connect;
db.api.close = & mysql_close;

// DBClass object holding the Mongo Api reference
db.api.init = & mongo_init;
db.api.connect = & mongo_connect;
db.api.close = & mongo_destroy;

Here is a basic example of usage.

// Test program
//
int main(void) {
    int status;
    DBClass db;

    // Init DBClass object with MYSQL Api reference
    db.api.init = & mysql_init;
    db.api.connect = & mysql_real_connect;
    db.api.close = & mysql_close;

    // Initializes MYSQL DB instance and call connect
    db.api.init(db.api.handle);
    status = (db.api.connect)(db.api.handle, "localhost:8080", "usr", "pwd", "default");

    // Init the same DBClass object with Mongo Api reference
    db.api.init = & mongo_init;
    db.api.connect = & mongo_connect;
    db.api.close = & mongo_destroy;

    // Initializes Mongo DB instance and call connect
    db.api.init(db.api.handle);
    status = (db.api.connect)(db.api.handle, "localhost:8080", "usr", "pwd", "default");

    return 0;
}

Final Word

It would be nice if this tutorial would’ve left you with some great ideas about creating a successful and rich C++ class-like framework using C programming. We would suggest you try out the things that you’ve learned from here. If you experiment with it later, then do share your experiences with us.

And if you like being here reading this particular post, please do share it with your friends or on social media of your choice.

Since legends have said that C programming is like an ocean to explore you can find out more details on Object-oriented programming using C language, follow the link.

Keep Learning,
TechBeamers

You Might Also Like

Basic Linux Commands for Beginners With Examples

How to Use Bash to Replace Character in String

Simple Bash Scripting Tutorial for Beginners

20 Bash Script Code Challenges for Beginners with Their Solutions

Difference Between Git Repository and Directory

Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article JNA Tutorial with Java Sample Program How to Write a Simple JNA Program in Java
Next Article How to install MongoDB on Ubuntu 14.04 Learn to Install MongoDB on Ubuntu

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x
x