C++ and Object-Oriented Programming

Classes and Objects; Constructors and Destructors

C-CAT

Classes and Objects

Class Definition

A class is a user-defined data type that serves as a blueprint for objects.

  • Contains data members (variables)
  • Contains member functions (methods)

An object is an instance of a class — a real entity created from the blueprint.

#include <iostream>
#include <string>
using namespace std;

// Class definition
class Employee {
private:
    int empID;
    string empName;
    double
empSalary;

public:
    // Member functions
    void AcceptData() {
        cout <<
"Enter EmpID: "; cin >> empID;
        cout << "Enter Name: "; cin >> empName;
        cout
<< "Enter Salary: "; cin >> empSalary;
    }

    void PrintEmpData() {
        cout <<
"ID: " << empID
             << ", Name: " << empName
             << ", Salary: " <<
empSalary << endl;
    }

    // Getters
    int getID() const { return empID; }
string getName() const { return empName; }
    double getSalary() const { return empSalary;
}
};

int main() {
    // Create objects
    Employee e1, e2;

    e1.AcceptData();    // e1 is one employee
    e1.PrintEmpData();

    // Create on heap
    Employee *eptr = new Employee();
    eptr->AcceptData();
    eptr->PrintEmpData();
    delete eptr;         // must delete heap objects

    return 0;
}

Empty Class

class Empty {};

// Size of object of empty class is always 1 byte
cout << sizeof(Empty) << endl;   // 1 (placeholder)

Object Identity

Employee e1, e2;
// Both are different objects with separate memory
cout << &e1 << " vs " << &e2 << endl;   // different addresses

Constructors and Destructors

What is a Constructor?

A constructor is a special member function that:

  • Has the same name as the class

Has no return type (not even void)

  • Is called automatically when an object is created
  • Used to initialize data members

Types of Constructors

7.1 Default Constructor (Parameterless)

class TDate {
private:
    int day, month, year;

public:
    // Default constructor
    TDate() {
        day = 1; month = 1; year = 2024;
        cout << "Default constructor called\n";
    }
};

TDate d1;   // Calls TDate() automatically

7.2 Parameterized Constructor

class TDate {
private:
    int day, month, year;

public:
    // Parameterized constructor
    TDate(int d, int m, int y) {
        day = d; month = m; year = y;
    }

    void PrintDate_dd_mm_yyyy() {
        cout << day << "-" << month << "-" << year << endl;
    }

    void PrintDate_dd_month_yyyy() {
        string months[] = {"", "January","February","March","April",
                           "May","June","July","August","September",
                           "October","November","December"};
        cout << day << "-" << months[month] << "-" << year << endl;
    }

    bool ValidateDate() {
        if (month < 1 || month > 12) return false;
        int days_in_month[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
        // Adjust for leap year
        bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        if (leap) days_in_month[2] = 29;
        if (day < 1 || day > days_in_month[month]) return false;
        return true;
    }
};

TDate d1(2, 5, 2022);   // Calls TDate(int, int, int)
d1.PrintDate_dd_mm_yyyy();       // 2-5-2022
d1.PrintDate_dd_month_yyyy();    // 2-May-2022

7.3 Constructor Overloading

class Complex {
private:
    double real, imaginary;

public:
    // Default constructor
    Complex() : real(0), imaginary(0) {}

    // Parameterized constructor
    Complex(double r, double i) : real(r), imaginary(i) {}

    // Accept complex number
    void accept() {
        cout << "Enter real: "; cin >> real;
        cout << "Enter imaginary: "; cin >> imaginary;
    }

    // Print complex number
    void print() const {
        if (imaginary >= 0)
            cout << real << " + " << imaginary << "i" << endl;
        else
            cout << real << " - " << (-imaginary) << "i" << endl;
    }

    // Add two complex numbers
    Complex add(const Complex &other) const {
        return Complex(real + other.real, imaginary + other.imaginary);
    }
};

Complex c1;              // Default: 0+0i
Complex c2(3.0, 4.0);   // Parameterized: 3+4i
c2.print();              // 3 + 4i

Destructor

A destructor is called automatically when an object goes out of scope or is deleted.

class Resource {
private:
    int *data;

public:
    Resource(int size) {
        data = new int[size];
        cout << "Constructor: memory allocated\n";
    }

    // Destructor: ~ prefix, no params, no return type
    ~Resource() {
        delete[] data;    // free memory
        data = nullptr;
        cout << "Destructor: memory freed\n";
    }
};

int main() {
    {
        Resource r(100);   // Constructor called
        // use r
    }                      // r goes out of scope → Destructor called automatically
    return 0;
}

Continue learning

Related notes

Put this topic into timed practice

Open mock tests when you want full-exam pacing, or keep drilling in practice mode.