CSC166 Object Oriented Programming

Object Oriented ProgrammingUnit 28 min read

Classes and Objects: Structure, Access, and Real-World Modeling

Unit 2 of Object Oriented Programming covers the core concepts of classes (blueprints) and objects (instances), including data members, member functions, access specifiers (public, private, protected), constructors/destructors, and object interaction. This note explains how to design classes, access members, and use ob


Core Concepts: Classes and Objects

1. What is a Class?

A class is a blueprint or template that defines the structure (data members) and behavior (member functions) of objects. It encapsulates data and functions into a single unit.

Example:

classDiagram
    class Car {
        -string model
        -int year
        +void display()
        +void setModel(string m)
    }
    class Person {
        -string name
        -Car car
        +void buyCar(Car c)
    }
    Person --> Car : owns
  • Data Members (Attributes): Variables that store data (e.g., model, year).
  • Member Functions (Methods): Functions that operate on data (e.g., display(), setModel()).

Why Classes?

  • Modularity: Group related data and functions.
  • Reusability: Create multiple objects from one class.
  • Data Hiding: Protect sensitive data using private access.

2. What is an Object?

An object is an instance of a class. It occupies memory and holds actual values.

Example:

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int roll;
    void display() {
        cout << "Name: " << name << ", Roll: " << roll << endl;
    }
};

int main() {
    Student s1; // Object creation
    s1.name = "Ramesh";
    s1.roll = 101;
    s1.display();
    return 0;
}

Output:

Name: Ramesh, Roll: 101

Visualization of Object Creation:

flowchart TD
    A["Class: Student"] -->|"Blueprint"| B["Object: s1"]
    B --> C["Memory Allocation\n(name: \"Ramesh\", roll: 101)"]

3. Access Specifiers: Public, Private, Protected

Access specifiers control how members of a class can be accessed.

Specifier Access Level Usage Example
public Accessible everywhere public: int age;
private Accessible only within the class private: string password;
protected Accessible within class and derived classes protected: int salary;

Example:

class BankAccount {
private:
    double balance;
public:
    void deposit(double amount) {
        balance += amount;
    }
    void displayBalance() {
        cout << "Balance: " << balance << endl;
    }
};

Why private?

  • Prevents unauthorized modification of data (e.g., balance in a bank account).

4. Member Functions

Functions defined inside a class to perform operations on its data.

Types of Member Functions:

  1. Instance Member Functions: Operate on object data (e.g., display()).
  2. Static Member Functions: Belong to the class, not objects (e.g., getCount()).
  3. Friend Functions: Non-member functions with access to private members.

Example: Static Member Function

class Counter {
private:
    static int count;
public:
    Counter() { count++; }
    static int getCount() { return count; }
};
int Counter::count = 0;

int main() {
    Counter c1, c2;
    cout << "Objects created: " << Counter::getCount(); // Output: 2
}

5. Constructors and Destructors

Constructors

  • Special member functions called when an object is created.
  • Used to initialize objects.

Types:

  1. Default Constructor: No arguments.
  2. Parameterized Constructor: Takes arguments.
  3. Copy Constructor: Initializes using another object.

Example:

class Rectangle {
private:
    int width, height;
public:
    Rectangle(int w, int h) { width = w; height = h; } // Parameterized
    int area() { return width * height; }
};

int main() {
    Rectangle r1(10, 5); // Constructor called
    cout << "Area: " << r1.area(); // Output: 50
}

Visualization of Constructor Execution:

flowchart TD
    A["Rectangle r1(10, 5);"] --> B["Memory Allocated\nwidth=10, height=5"]
    B --> C["Constructor Called\nInitializes width & height"]

Destructors

  • Called when an object is destroyed.
  • Used for cleanup (e.g., releasing memory).

Example:

class FileHandler {
public:
    ~FileHandler() { cout << "File closed." << endl; }
};

int main() {
    FileHandler f;
    // Destructor called when 'f' goes out of scope
}

6. this Pointer

  • Points to the current object.
  • Used to resolve naming conflicts (e.g., member variable vs. parameter).

Example:

class Person {
private:
    string name;
public:
    void setName(string name) {
        this->name = name; // 'this->name' refers to member, 'name' is parameter
    }
};

In the Real World

  1. eSewa (Nepal):

    • Class: User, Transaction
    • Objects: Each user (e.g., user1, user2) is an instance of User.
    • Member Functions: payBill(), checkBalance().
    • Access Specifiers: private for password, public for userID.
  2. Khalti (Digital Payments):

    • Class: Wallet
    • Objects: Each user’s wallet (e.g., wallet1, wallet2).
    • Constructor: Initializes balance when a new account is created.
    • Destructor: Cleans up temporary session data.
  3. Bank Loan Calculation (Nepal):

    • Class: Loan
    • Data Members: principal, interestRate, duration.
    • Member Function: calculateEMI() computes monthly payments.
    • Example Trace:
      Loan loan1(1000000, 8.5, 5); // Principal: 1M, Rate: 8.5%, Duration: 5 years
      cout << "EMI: " << loan1.calculateEMI(); // Output: ~19,800 NPR/month
      

7. Object Interaction: Passing Objects as Arguments

Objects can be passed to functions by:

  • Value: Copies the object.
  • Reference: Passes the object directly (efficient for large objects).

Example: Passing by Reference

void incrementAge(Person &p) {
    p.age++; // Modifies the original object
}

int main() {
    Person p1;
    incrementAge(p1); // p1.age increases
}

Visualization of Pass-by-Reference:

flowchart TD
    A["Person p1;"] --> B["Memory Address\n&p1"]
    B --> C["incrementAge(p1)"] --> D["Modifies p1.age directly"]

8. Arrays of Objects

Store multiple objects of the same class in an array.

Example:

class Student {
public:
    string name;
    int marks;
};

int main() {
    Student students[3] = {
        {"Ramesh", 85},
        {"Sita", 90},
        {"Hari", 78}
    };
    for (int i = 0; i < 3; i++) {
        cout << students[i].name << ": " << students[i].marks << endl;
    }
}

Output:

Ramesh: 85
Sita: 90
Hari: 78

9. Dynamic Memory Allocation for Objects

Use new and delete to create objects dynamically.

Example:

class DynamicObject {
public:
    int data;
    DynamicObject(int d) { data = d; }
};

int main() {
    DynamicObject *obj = new DynamicObject(100); // Dynamic allocation
    cout << obj->data; // Output: 100
    delete obj; // Free memory
}

Visualization of Dynamic Allocation:

flowchart TD
    A["DynamicObject *obj = new DynamicObject(100);"] --> B["Heap Memory\nobj->data=100"]
    B --> C["delete obj;"] --> D["Memory Freed"]

Exam Tip

  1. Class vs. Object:

    • Class = Blueprint (e.g., Car).
    • Object = Instance (e.g., myCar).
    • Exam Question: "Define class and object with an example." → Always include both definition and a code snippet.
  2. Access Specifiers:

    • private is default in C++ (unlike Java).
    • Exam Question: "How are members of a class accessed?" → Explain public, private, and protected with examples.
  3. Constructors/Destructors:

    • Default constructor is called if no constructor is defined.
    • Exam Question: "Write a program to create a class with a parameterized constructor." → Include initialization and object creation.
  4. Object Interaction:

    • Pass by reference is preferred for efficiency.
    • Exam Question: "Write a function to compare two objects of a class." → Use member functions and return the object with lower value.
  5. Real-World Applications:

    • eSewa/Khalti: Model as classes with private data (e.g., password) and public functions (e.g., payBill()).
    • Bank Loans: Use constructors to initialize loan terms and member functions to compute EMI.
  6. Common Pitfalls:

    • Forgetting to initialize objects (use constructors).
    • Misusing this pointer (e.g., this->variable vs. variable).
    • Memory leaks (always delete dynamically allocated objects).

Practice Questions for TU/PU Exams:

  1. Create a Book class with title and price. Write a function to return the cheaper book between two objects.
  2. Write a program to store 5 Student objects in an array and display their details.
  3. Explain the difference between pass-by-value and pass-by-reference with an example.
  4. Define a BankAccount class with deposit() and withdraw() methods. Use private for balance.

Based on the TU BSc CSIT syllabus for Object Oriented Programming (CSC166), unit 2.

Discussion

Loading…