In this section, we will delve into the core concepts of Object-Oriented Programming (OOP) in C++: classes and objects. Understanding these concepts is crucial for writing modular, reusable, and maintainable code.

Key Concepts

  1. Class: A blueprint for creating objects. It defines a datatype by bundling data and methods that work on the data into one single unit.
  2. Object: An instance of a class. When a class is defined, no memory is allocated until an object of that class is created.
  3. Member Variables: Variables defined inside a class.
  4. Member Functions: Functions defined inside a class.

Defining a Class

A class is defined using the class keyword followed by the class name and a pair of curly braces {}. Inside the curly braces, you define member variables and member functions.

class Car {
public:
    // Member Variables
    string brand;
    string model;
    int year;

    // Member Functions
    void displayInfo() {
        cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << endl;
    }
};

Explanation

  • Access Specifiers: public, private, and protected are access specifiers. They define the access level of the members of the class.

    • public: Members are accessible from outside the class.
    • private: Members are accessible only within the class.
    • protected: Members are accessible within the class and by derived class.
  • Member Variables: brand, model, and year are member variables of the class Car.

  • Member Functions: displayInfo() is a member function that prints the car's information.

Creating Objects

To create an object of a class, you simply declare a variable of the class type.

int main() {
    Car car1; // Create an object of Car

    // Accessing and modifying member variables
    car1.brand = "Toyota";
    car1.model = "Corolla";
    car1.year = 2020;

    // Calling member function
    car1.displayInfo();

    return 0;
}

Explanation

  • Car car1; creates an object car1 of the class Car.
  • car1.brand = "Toyota"; assigns the value "Toyota" to the brand member variable of car1.
  • car1.displayInfo(); calls the displayInfo member function of car1.

Practical Example

Let's create a more comprehensive example with multiple member functions and private member variables.

#include <iostream>
using namespace std;

class BankAccount {
private:
    string accountNumber;
    double balance;

public:
    // Constructor
    BankAccount(string accNum, double initialBalance) {
        accountNumber = accNum;
        balance = initialBalance;
    }

    // Member Functions
    void deposit(double amount) {
        balance += amount;
        cout << "Deposited: $" << amount << endl;
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
            cout << "Withdrew: $" << amount << endl;
        } else {
            cout << "Insufficient balance!" << endl;
        }
    }

    void displayBalance() {
        cout << "Account Number: " << accountNumber << ", Balance: $" << balance << endl;
    }
};

int main() {
    // Create an object of BankAccount
    BankAccount account1("123456789", 1000.0);

    // Perform operations
    account1.deposit(500.0);
    account1.withdraw(200.0);
    account1.displayBalance();

    return 0;
}

Explanation

  • Constructor: BankAccount(string accNum, double initialBalance) initializes the member variables accountNumber and balance.
  • Member Functions: deposit, withdraw, and displayBalance perform operations on the balance and display the account information.

Exercises

Exercise 1: Define a Class

Define a class Student with the following member variables and functions:

  • Member Variables: name, age, grade
  • Member Functions: setDetails, getDetails
#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;
    char grade;

    void setDetails(string n, int a, char g) {
        name = n;
        age = a;
        grade = g;
    }

    void getDetails() {
        cout << "Name: " << name << ", Age: " << age << ", Grade: " << grade << endl;
    }
};

int main() {
    Student student1;
    student1.setDetails("John Doe", 20, 'A');
    student1.getDetails();

    return 0;
}

Exercise 2: Private Members

Modify the Student class to make name, age, and grade private. Add public member functions to set and get these values.

#include <iostream>
using namespace std;

class Student {
private:
    string name;
    int age;
    char grade;

public:
    void setDetails(string n, int a, char g) {
        name = n;
        age = a;
        grade = g;
    }

    void getDetails() {
        cout << "Name: " << name << ", Age: " << age << ", Grade: " << grade << endl;
    }
};

int main() {
    Student student1;
    student1.setDetails("John Doe", 20, 'A');
    student1.getDetails();

    return 0;
}

Common Mistakes and Tips

  • Access Specifiers: Ensure you understand the difference between public, private, and protected. Use private for member variables to enforce encapsulation.
  • Initialization: Always initialize member variables, either through constructors or directly.
  • Object Creation: Remember that creating an object of a class allocates memory for the member variables.

Conclusion

In this section, we covered the basics of classes and objects in C++. We learned how to define a class, create objects, and use member variables and functions. These concepts form the foundation of Object-Oriented Programming and are essential for writing structured and efficient C++ code. In the next section, we will explore constructors and destructors, which are special member functions used for initializing and cleaning up objects.

© Copyright 2024. All rights reserved