0
0
C++programming~7 mins

Procedural vs OOP approach in C++

Choose your learning style9 modes available
Introduction

We use different ways to organize code to make it easier to understand and change. Procedural and OOP are two common ways to do this.

When you want to write simple programs that follow step-by-step instructions.
When you want to group data and actions together to model real-world things.
When your program grows bigger and you want to keep code organized and reusable.
When you want to share code easily between different parts of your program.
When you want to protect data and control how it is changed.
Syntax
C++
/* Procedural approach example */
#include <iostream>
void printSum(int a, int b) {
    int sum = a + b;
    std::cout << "Sum: " << sum << std::endl;
}

/* OOP approach example */
class Calculator {
public:
    int add(int a, int b) {
        return a + b;
    }
};

Procedural code focuses on functions and the sequence of steps.

OOP groups data and functions inside classes to represent objects.

Examples
This example shows a simple function called directly in procedural style.
C++
#include <iostream>

// Procedural style
void greet() {
    std::cout << "Hello!" << std::endl;
}

int main() {
    greet();
    return 0;
}
This example shows a class with a method, and an object calling that method.
C++
#include <iostream>

// OOP style
class Greeter {
public:
    void greet() {
        std::cout << "Hello!" << std::endl;
    }
};

int main() {
    Greeter g;
    g.greet();
    return 0;
}
Sample Program

This program shows how to calculate area of a rectangle using both procedural and OOP ways.

C++
#include <iostream>

// Procedural approach
void printArea(int width, int height) {
    int area = width * height;
    std::cout << "Procedural area: " << area << std::endl;
}

// OOP approach
class Rectangle {
    int width, height;
public:
    Rectangle(int w, int h) : width(w), height(h) {}
    int area() {
        return width * height;
    }
};

int main() {
    // Using procedural function
    printArea(5, 3);

    // Using OOP class
    Rectangle rect(5, 3);
    std::cout << "OOP area: " << rect.area() << std::endl;

    return 0;
}
OutputSuccess
Important Notes

Procedural code is easier for small tasks but can get messy as programs grow.

OOP helps organize code by bundling data and actions, making it easier to manage large projects.

Choosing between them depends on the problem and your goals.

Summary

Procedural programming uses functions and step-by-step instructions.

Object-Oriented Programming groups data and functions inside classes called objects.

OOP is good for modeling real-world things and managing bigger programs.