Difference Between C and C++

C++ was developed as an extension of the C programming language, adding object-oriented features while maintaining compatibility with C. Here’s a comprehensive comparison of these two languages:

Basic Differences

FeatureCC++
ParadigmProcedural programming languageMulti-paradigm: procedural, object-oriented, generic, functional
FocusAlgorithm-oriented (focus on “how to do”)Object-oriented (focus on “what to do”)
ApproachTop-down approachBottom-up approach
DevelopmentDeveloped by Dennis Ritchie in 1972Developed by Bjarne Stroustrup in 1979 as “C with Classes”
File Extension.c.cpp, .cxx, or .cc

Programming Paradigm Differences

C (Procedural)

  • Programs are divided into functions
  • Functions operate on data that’s separate from functions
  • Follow a top-down approach to problem-solving
  • Focus on steps and procedures

C++ (Object-Oriented & More)

  • Programs are divided into objects
  • Objects contain both data and functions that operate on the data
  • Follow a bottom-up approach to problem-solving
  • Focus on data and the operations that can be performed on it
  • Supports multiple paradigms including procedural, object-oriented, generic, and functional

Key Features in C++ Not Available in C

1. Classes and Objects

C++ introduced the concept of classes and objects, which is the foundation of object-oriented programming.

// C++ class example
class Student {
private:
    int rollNumber;
    std::string name;
    
public:
    Student(int roll, std::string studentName) {
        rollNumber = roll;
        name = studentName;
    }
    
    void display() {
        std::cout << "Roll Number: " << rollNumber << std::endl;
        std::cout << "Name: " << name << std::endl;
    }
};

int main() {
    Student s1(101, "John");
    s1.display();
    return 0;
}

2. Encapsulation

C++ allows bundling data and methods into a single unit (class) and restricting access.

class BankAccount {
private:
    double balance;  // Private data, not accessible outside the class
    
public:
    // Public methods to access/modify private data
    void deposit(double amount) {
        if (amount > 0)
            balance += amount;
    }
    
    double getBalance() {
        return balance;
    }
};

3. Inheritance

C++ supports creating new classes based on existing ones.

class Vehicle {
protected:
    std::string brand;
    
public:
    void setBrand(std::string b) {
        brand = b;
    }
    
    void displayInfo() {
        std::cout << "Brand: " << brand << std::endl;
    }
};

class Car : public Vehicle {
private:
    int numDoors;
    
public:
    void setDoors(int d) {
        numDoors = d;
    }
    
    void display() {
        displayInfo();  // Access parent method
        std::cout << "Number of doors: " << numDoors << std::endl;
    }
};

4. Polymorphism

C++ allows objects of different classes to be treated as objects of a common base class.

class Shape {
public:
    virtual void draw() {
        std::cout << "Drawing a shape" << std::endl;
    }
};

class Circle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a circle" << std::endl;
    }
};

class Rectangle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a rectangle" << std::endl;
    }
};

// Polymorphic behavior
void drawShape(Shape* s) {
    s->draw();  // Calls the appropriate draw method
}

5. Function Overloading

C++ allows multiple functions with the same name but different parameters.

void print(int i) {
    std::cout << "Integer: " << i << std::endl;
}

void print(double d) {
    std::cout << "Double: " << d << std::endl;
}

void print(std::string s) {
    std::cout << "String: " << s << std::endl;
}

6. Operator Overloading

C++ allows redefining operators for user-defined types.

class Complex {
private:
    double real, imag;
    
public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}
    
    Complex operator+(const Complex& obj) {
        Complex result;
        result.real = real + obj.real;
        result.imag = imag + obj.imag;
        return result;
    }
};

7. References

C++ introduced reference variables as alternatives to pointers.

void swapUsingReferences(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

// Usage
int x = 10, y = 20;
swapUsingReferences(x, y);  // x becomes 20, y becomes 10

8. Exception Handling

C++ provides built-in support for exception handling.

try {
    int division = 10 / 0;  // Causes an exception
} catch (const std::exception& e) {
    std::cout << "Exception occurred: " << e.what() << std::endl;
}

9. Namespaces

C++ allows grouping entities like classes, objects, and functions under a name.

namespace Mathematics {
    double PI = 3.14159;
    
    double square(double x) {
        return x * x;
    }
}

// Using namespace
double area = Mathematics::PI * Mathematics::square(5);

10. Templates

C++ supports generic programming through templates.

template <typename T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}

// Usage with different types
int maxInt = maximum<int>(10, 20);
double maxDouble = maximum<double>(10.5, 20.7);

Input/Output Differences

C

Uses functions from standard libraries:

#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("You entered: %d\n", num);
    return 0;
}

C++

Uses stream-based I/O:

#include <iostream>

int main() {
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;
    std::cout << "You entered: " << num << std::endl;
    return 0;
}

Memory Management Differences

C

  • Uses functions like malloc(), calloc(), realloc(), and free()
  • Manual memory management
  • No constructor/destructor concepts
#include <stdlib.h>

int main() {
    // Allocate memory
    int* arr = (int*)malloc(5 * sizeof(int));
    
    // Use the memory
    for(int i = 0; i < 5; i++) {
        arr[i] = i + 1;
    }
    
    // Free memory
    free(arr);
    return 0;
}

C++

  • Uses operators new and delete
  • Supports constructors and destructors for initialization and cleanup
  • Smart pointers for automatic memory management (C++11 onwards)
#include <iostream>
#include <memory>  // for smart pointers

int main() {
    // Using new/delete
    int* arr = new int[5];
    for(int i = 0; i < 5; i++) {
        arr[i] = i + 1;
    }
    delete[] arr;
    
    // Using smart pointers (C++11)
    std::unique_ptr<int[]> smartArr(new int[5]);
    for(int i = 0; i < 5; i++) {
        smartArr[i] = i + 1;
    }
    // No need to delete - memory automatically freed
    
    return 0;
}

File Handling Differences

C

Uses functions from stdio.h:

#include <stdio.h>

int main() {
    FILE* file = fopen("data.txt", "w");
    fprintf(file, "Hello, C file handling!");
    fclose(file);
    return 0;
}

C++

Uses file streams:

#include <fstream>
#include <string>

int main() {
    std::ofstream file("data.txt");
    file << "Hello, C++ file handling!";
    file.close();
    return 0;
}

Structures and Classes

C

Structures can only contain data members:

struct Person {
    char name[50];
    int age;
};

void displayPerson(struct Person p) {
    printf("Name: %s, Age: %d\n", p.name, p.age);
}

C++

Structures and classes can contain both data and methods:

class Person {
private:
    std::string name;
    int age;
    
public:
    Person(std::string n, int a) : name(n), age(a) {}
    
    void display() {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

Compatibility

C++ is mostly backward compatible with C, meaning most C code can be compiled with a C++ compiler. However, some differences exist:

  1. C++ treats function prototypes more strictly
  2. C allows implicit conversion between void* and other pointer types, C++ requires explicit casting
  3. Some C keywords are reserved in C++
  4. C++ has stricter type checking

Performance Considerations

  1. Compilation: C++ typically requires more compilation time due to its complex features
  2. Runtime Performance: Basic C and C++ constructs have similar performance, but some C++ features (like virtual functions) may introduce overhead
  3. Memory Usage: C++ programs may use more memory due to features like virtual function tables
  4. Optimization: Both languages allow for high-level optimization

When to Choose Which Language

Choose C When:

  • Developing low-level system software (operating systems, device drivers)
  • Working with very limited hardware resources
  • Maximum performance and minimal overhead are critical
  • Compatibility with existing C codebases is necessary
  • Simplicity is preferred over advanced features

Choose C++ When:

  • Developing large, complex applications
  • Object-oriented design is beneficial
  • Code reusability and maintainability are important
  • Generic programming with templates is needed
  • Exception handling would simplify error management
  • Working with existing C++ libraries or frameworks

Conclusion

While C++ includes all the features of C, it adds significant enhancements, particularly in the area of object-oriented programming. The choice between C and C++ depends on the specific requirements of your project, such as performance constraints, complexity, and design paradigms. C++ offers more features and flexibility, but C may be preferable for certain low-level or performance-critical applications.