Class and Object

Programming

Classes are user-defined types that encapsulate data (member variables) and functions (member functions). Objects are instances of classes. This is the foundation of object-oriented programming in C++.

Basic Example

#include <iostream>

class Rectangle {
public:
    int length, width;

    int area() {
        return length * width;
    }
};

int main() {
    Rectangle rect;
    rect.length = 5;
    rect.width = 3;

    std::cout << "Area of rectangle: " << rect.area() << std::endl;
    return 0;
}

Access Specifiers

C++ provides three access levels for class members:

Encapsulation Example

A better design uses private members with public accessors:

#include <iostream>

class Rectangle {
private:
    int length;
    int width;

public:
    // Constructor
    Rectangle(int l, int w) : length(l), width(w) {}
    
    // Getters
    int getLength() const { return length; }
    int getWidth() const { return width; }
    
    // Setters with validation
    void setLength(int l) {
        if (l > 0) length = l;
    }
    
    void setWidth(int w) {
        if (w > 0) width = w;
    }
    
    // Member functions
    int area() const {
        return length * width;
    }
    
    int perimeter() const {
        return 2 * (length + width);
    }
};

int main() {
    Rectangle rect(5, 3);
    std::cout << "Area: " << rect.area() << std::endl;
    std::cout << "Perimeter: " << rect.perimeter() << std::endl;
    
    return 0;
}

Constructors and Destructors

#include <iostream>
#include <string>

class Person {
private:
    std::string name;
    int age;

public:
    // Default constructor
    Person() : name("Unknown"), age(0) {
        std::cout << "Default constructor called" << std::endl;
    }
    
    // Parameterized constructor
    Person(const std::string& n, int a) : name(n), age(a) {
        std::cout << "Parameterized constructor called" << std::endl;
    }
    
    // Destructor
    ~Person() {
        std::cout << "Destructor called for " << name << std::endl;
    }
    
    void display() const {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    Person p1;  // Default constructor
    Person p2("Alice", 25);  // Parameterized constructor
    p2.display();
    // Destructors called automatically when objects go out of scope
    return 0;
}

Key Concepts

Best Practices

Common Pitfalls

Output

Area of rectangle: 15