Classes in C++

What is a Class in C++?

A class in C++ is a user-defined data type that serves as a blueprint for creating objects. It encapsulates data (attributes) and functions (methods) that operate on that data into a single unit.

Class Structure in C++

class ClassName {
    // Access specifier
private:
    // Private data members and member functions
    
protected:
    // Protected data members and member functions
    
public:
    // Public data members and member functions
};

Access Specifiers in C++

C++ classes use three access specifiers to control the visibility and accessibility of class members:

  1. public: Members are accessible from anywhere in the program, including outside the class
  2. private: Members are only accessible within the class itself
  3. protected: Members are accessible within the class and its derived classes (child classes)

Example:

class Student {
private:
    // Private data members (only accessible within the class)
    int rollNumber;
    float marks;

protected:
    // Protected data members (accessible in this class and derived classes)
    string address;

public:
    // Public data members (accessible anywhere)
    string name;
    
    // Public member functions
    void setRollNumber(int roll) {
        rollNumber = roll;
    }
    
    int getRollNumber() {
        return rollNumber;
    }
    
    void displayDetails() {
        cout << "Name: " << name << endl;
        cout << "Roll Number: " << rollNumber << endl;
        cout << "Marks: " << marks << endl;
    }
};

Default Access Specifier

If you don’t specify an access specifier, the default is private for classes and public for structures.

class MyClass {
    int x;  // Private by default
    void func() { }  // Private by default
};

struct MyStruct {
    int x;  // Public by default
    void func() { }  // Public by default
};

Data Members in a Class

Data members are variables declared inside a class. They represent the attributes or characteristics of the class.

class Car {
private:
    string brand;    // Data member
    string model;    // Data member
    int year;        // Data member
    float price;     // Data member
};

Types of Data Members:

  1. Instance Variables: Each object has its own copy
  2. Static Variables: Shared among all objects of the class
  3. Constant Variables: Values that cannot be changed

Member Functions in a Class

Member functions are functions declared within a class. They define the behaviors or operations that objects of the class can perform.

class Rectangle {
private:
    double length;
    double width;
    
public:
    // Member functions
    void setDimensions(double l, double w) {
        length = l;
        width = w;
    }
    
    double calculateArea() {
        return length * width;
    }
    
    double calculatePerimeter() {
        return 2 * (length + width);
    }
};

Types of Member Functions:

  1. Accessor Functions (Getters): Access data without modifying it
  2. Mutator Functions (Setters): Modify data members
  3. Constructor Functions: Initialize objects when created
  4. Destructor Functions: Clean up resources when objects are destroyed
  5. Static Member Functions: Can be called without an object
  6. Const Member Functions: Cannot modify class data

Class Declaration vs. Definition

You can declare a class and define its functions separately:

// Class declaration
class Circle {
private:
    double radius;
    
public:
    // Function declarations
    void setRadius(double r);
    double getRadius();
    double calculateArea();
    double calculateCircumference();
};

// Function definitions
void Circle::setRadius(double r) {
    radius = r;
}

double Circle::getRadius() {
    return radius;
}

double Circle::calculateArea() {
    return 3.14159 * radius * radius;
}

double Circle::calculateCircumference() {
    return 2 * 3.14159 * radius;
}

Creating Objects of a Class

Once a class is defined, you can create objects of that class type:

int main() {
    // Creating objects
    Circle circle1;       // First object
    Circle circle2;       // Second object
    Circle* circlePtr;    // Pointer to Circle object
    
    // Using objects
    circle1.setRadius(5.0);
    cout << "Area of circle1: " << circle1.calculateArea() << endl;
    
    // Dynamic object creation
    circlePtr = new Circle();
    circlePtr->setRadius(7.5);
    cout << "Area of circle pointed by circlePtr: " << circlePtr->calculateArea() << endl;
    delete circlePtr;  // Don't forget to free the memory
    
    return 0;
}

Accessing Class Members

You access class members using the following operators:

  1. Dot Operator (.): Used with object names

    Student s1;
    s1.name = "John";
    s1.displayDetails();
  2. Arrow Operator (->): Used with object pointers

    Student* ptr = new Student();
    ptr->name = "Alice";
    ptr->displayDetails();

Scope Resolution Operator (::)

The scope resolution operator :: is used to define member functions outside of the class or to access static members:

// Function defined outside the class
void Student::displayDetails() {
    cout << "Name: " << name << endl;
    cout << "Roll Number: " << rollNumber << endl;
}

// Accessing a static member
int Student::objectCount = 0;

Advantages of C++ Classes

  1. Encapsulation: Bundle data and functions into a single unit
  2. Data Hiding: Control access to data using access specifiers
  3. Code Reusability: Create multiple objects from the same class
  4. Inheritance: Create new classes based on existing classes
  5. Polymorphism: Use objects of different classes through the same interface

Classes vs. Structs in C++

In C++, both classes and structs can contain data members and member functions, but they have some differences:

ClassesStructs
Default access is privateDefault access is public
Usually used for objects with behaviorOften used for simple data structures
Used when encapsulation is importantUsed when direct data access is needed
// Class example
class Person {
private:  // Private by default
    string name;
    int age;
public:
    void setDetails(string n, int a) {
        name = n;
        age = a;
    }
};

// Struct example
struct Point {
    int x;  // Public by default
    int y;  // Public by default
};

Best Practices for C++ Classes

  1. Keep the interface simple: Only expose what’s necessary
  2. Validate input: Check parameters in setters and constructors
  3. Use meaningful names: Name classes and members clearly
  4. Follow encapsulation: Make data members private and provide access through methods
  5. Initialize members: Always initialize members in constructors
  6. Use const correctly: Mark methods that don’t modify the object as const

Complete Class Example

Here’s a complete example of a class in C++:

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

class BankAccount {
private:
    string accountHolder;
    string accountNumber;
    double balance;
    
public:
    // Constructor
    BankAccount(string holder, string number, double initialBalance) {
        accountHolder = holder;
        accountNumber = number;
        balance = initialBalance;
    }
    
    // Accessor methods (getters)
    string getAccountHolder() const {
        return accountHolder;
    }
    
    string getAccountNumber() const {
        return accountNumber;
    }
    
    double getBalance() const {
        return balance;
    }
    
    // Mutator methods (setters)
    void setAccountHolder(string holder) {
        accountHolder = holder;
    }
    
    // Behavior methods
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "Deposited: $" << amount << endl;
        } else {
            cout << "Invalid deposit amount" << endl;
        }
    }
    
    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            cout << "Withdrawn: $" << amount << endl;
        } else {
            cout << "Invalid withdrawal amount or insufficient funds" << endl;
        }
    }
    
    void displayDetails() const {
        cout << "Account Holder: " << accountHolder << endl;
        cout << "Account Number: " << accountNumber << endl;
        cout << "Balance: $" << balance << endl;
    }
};

int main() {
    // Create a bank account object
    BankAccount account1("John Doe", "AC1234567", 1000.0);
    
    // Display initial details
    cout << "Initial Account Details:" << endl;
    account1.displayDetails();
    
    // Perform operations
    account1.deposit(500.0);
    account1.withdraw(200.0);
    
    // Display updated details
    cout << "\nUpdated Account Details:" << endl;
    account1.displayDetails();
    
    return 0;
}

Summary

Classes in C++ are powerful constructs that allow you to create user-defined data types combining data and functions into a single unit. They provide encapsulation, data hiding, and form the foundation for object-oriented programming in C++. By understanding how to define and use classes effectively, you can create well-structured, maintainable, and reusable code.