3.3 C++ Language Constructs with Objects and Classes

1. Namespace

  • A namespace organizes code and prevents naming conflicts between variables, functions, or classes.

  • Example: The standard C++ library is contained within the std namespace.

#include <iostream>
// Using a namespace
namespace MyNamespace {
    int value = 100;
}

int main() {
    std::cout << "Value in MyNamespace: " << MyNamespace::value << std::endl;
    // Output: Value in MyNamespace: 100
    return 0;
}

2. Function Overloading

  • Function overloading allows multiple functions with the same name but different parameter types or numbers of parameters.

  • The compiler differentiates between them based on the argument list.

#include <iostream>
using namespace std;

// Function Overloading Example
void display(int num) {
    cout << "Integer: " << num << endl; // Output: Integer: 5
}

void display(double num) {
    cout << "Double: " << num << endl; // Output: Double: 5.5
}

int main() {
    display(5);    // Calls the integer version
    display(5.5);  // Calls the double version
    return 0;
}

3. Inline Functions

  • Inline functions reduce function call overhead by embedding the function code directly into the calling code during compilation.

  • Use the inline keyword before the function definition.

#include <iostream>
using namespace std;

inline int square(int x) {
    return x * x;  // Inline function logic
}

int main() {
    cout << "Square of 5: " << square(5) << endl; // Output: Square of 5: 25
    return 0;
}

4. Default Arguments

  • Default arguments allow a function to be called with fewer arguments by specifying default values for some parameters.

  • Default arguments must be specified from right to left in the parameter list.

#include <iostream>
using namespace std;

// Function with Default Arguments
void greet(string name = "Guest") {
    cout << "Hello, " << name << "!" << endl;
}

int main() {
    greet();          // Output: Hello, Guest!
    greet("Alice");   // Output: Hello, Alice!
    return 0;
}

5. Classes and Objects

  • Classes are user-defined data types that represent real-world entities, encapsulating data members and member functions.

  • Objects are instances of classes.

#include <iostream>
using namespace std;

class Rectangle {
public:
    int length, width;

    // Member function
    int area() {
        return length * width;
    }
};

int main() {
    Rectangle rect;       // Create an object of the class
    rect.length = 10;
    rect.width = 5;

    cout << "Area: " << rect.area() << endl; // Output: Area: 50
    return 0;
}

6. Constructors and Destructors

  • Constructors initialize objects when they are created. They share the same name as the class and have no return type.

  • Destructors clean up resources when the object is destroyed. They have the same name as the class but are preceded by a ~.

#include <iostream>
using namespace std;

class Demo {
public:
    Demo() { // Constructor
        cout << "Constructor called!" << endl; 
    }
    ~Demo() { // Destructor
        cout << "Destructor called!" << endl;
    }
};

int main() {
    Demo obj; // Constructor is called here
    // Destructor is automatically called at the end of the program
    return 0;
}

7. Dynamic Memory Allocation

  • C++ provides new and delete operators for dynamic memory allocation and deallocation.

#include <iostream>
using namespace std;

int main() {
    // Allocate memory dynamically
    int* ptr = new int(42); 
    cout << "Value: " << *ptr << endl; // Output: Value: 42

    delete ptr; // Deallocate memory
    return 0;
}

8. Friend Functions

  • A friend function has access to private and protected members of a class. It is declared using the friend keyword inside the class.

#include <iostream>
using namespace std;

class Box {
private:
    int length;
public:
    Box(int l) : length(l) {}
    friend void printLength(Box b); // Friend function declaration
};

void printLength(Box b) {
    cout << "Length: " << b.length << endl; // Access private member
}

int main() {
    Box box(10);
    printLength(box); // Output: Length: 10
    return 0;
}

Conclusion

C++ is a powerful object-oriented programming language that supports advanced features such as namespaces, function overloading, inline functions, default arguments, classes and objects, constructors and destructors, dynamic memory allocation, and friend functions. These features provide flexibility, reusability, and efficiency, enabling developers to create robust and scalable software. With its rich standard library and versatile constructs, C++ remains a top choice for applications ranging from system software to complex simulations and games.

Last updated