» Quick Introduction to C++ » 1. Basics » 1.8 Classes

Classes

Classes in C++ provide a way to structure and organize code in an object-oriented manner. Object-oriented programmin (OOP) is a programming paradigm that revolves around the concept of objects, which encapsulate data and behavior. Classes serve as blueprints or templates for creating objects.

Methods

Methods are functions that are associated with a class. They are sometimes referred to as member functions because they operate on the members (data) of the class.

#include <iostream>

// Declaration of the class
class Rectangle {
public:
    // Member variables (data members)
    double length;
    double width;

    // Member functions (methods)
    double calculateArea() {
        return length * width;
    }
};

int main() {
    // Creating an instance of the class (an object)
    Rectangle myRectangle;
    myRectangle.length = 5.0;
    myRectangle.width = 3.0;

    // Accessing member functions to perform calculations
    double area = myRectangle.calculateArea();

    std::cout << "Rectangle Area: " << area << std::endl;

    return 0;
}

Constructors & Destructors

Constructors and destructors are special member functions in C++ classes that are used for initialization and cleanup, respectively. Constructors are called when an object is created, and destructors are called when an object goes out of scope or is explicitly deleted.

#include <iostream>

// Declaration of the class
class Rectangle {
public:
    // Constructor (default constructor)
    Rectangle() {
        std::cout << "Default Constructor called" << std::endl;
        length = 0.0;
        width = 0.0;
    }

    // Parameterized constructor
    Rectangle(double len, double wid) {
        std::cout << "Parameterized Constructor called" << std::endl;
        length = len;
        width = wid;
    }

    // Member function to set the dimensions of the rectangle
    void setDimensions(double len, double wid) {
        length = len;
        width = wid;
    }

    // Member function to calculate the area of the rectangle
    double calculateArea() {
        return length * width;
    }

    // Destructor
    ~Rectangle() {
        std::cout << "Destructor called" << std::endl;
    }

private:
    // Member variables
    double length;
    double width;
};

int main() {
    // Creating an instance of the class using the default constructor
    Rectangle defaultRectangle;

    // Creating an instance of the class using the parameterized constructor
    Rectangle customRectangle(5.0, 3.0);

    // Using a method to set the dimensions
    customRectangle.setDimensions(8.0, 4.0);

    // Using methods to calculate the area
    double areaDefault = defaultRectangle.calculateArea();
    double areaCustom = customRectangle.calculateArea();

    // Displaying the results
    std::cout << "Area of Default Rectangle: " << areaDefault << std::endl;
    std::cout << "Area of Custom Rectangle: " << areaCustom << std::endl;

    // Destructor for customRectangle is called when it goes out of scope
    return 0;
}

Encapsulation

Encapsulation is one of the fundamental principles of object-oriented programming (OOP) and is a key feature of C++. It involves bundling the data (attributes) and the methods (functions) that operate on the data into a single unit called a class. Access to the data is controlled by providing public, private, and protected access specifiers.

Note that, in the previous code example, length and width are private member variables of the Rectangle class. They can only be accessed within the class.

Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows a new class (called a derived or child class) to inherit properties and behaviors from an existing class (called a base or parent class). In C++, you can achieve inheritance using the class keyword and the : (colon) symbol.

#include <iostream>

// Base class (parent class)
class Shape {
protected:
    double width;
    double height;

public:
    Shape(double w, double h) : width(w), height(h) {}

    // Virtual function for calculating area
    virtual double calculateArea() const {
        return width * height;
    }
};

// Derived class (child class)
class Rectangle : public Shape {
public:
    // Constructor for Rectangle, initializing base class using initialization list
    Rectangle(double w, double h) : Shape(w, h) {}

    // Overriding the calculateArea method
    double calculateArea() const override {
        return width * height;
    }
};

int main() {
    // Creating objects of the derived classes
    Rectangle myRectangle(5.0, 3.0);

    // Using the overridden calculateArea method
    double areaRectangle = myRectangle.calculateArea();

    // Displaying the results
    std::cout << "Area of Rectangle: " << areaRectangle << std::endl;

    return 0;
}

Polymorphism

Polymorphism is a key concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type.

#include <iostream>

class Shape {
public:
    virtual double calculateArea() const {
        return 0.0; // Default implementation for the base class
    }
};

class Rectangle : public Shape {
private:
    double width;
    double height;

public:
    Rectangle(double w, double h) : width(w), height(h) {}

    // Overriding the calculateArea method
    double calculateArea() const override {
        return width * height;
    }
};

class Triangle : public Shape {
private:
    double base;
    double height;

public:
    Triangle(double b, double h) : base(b), height(h) {}

    // Overriding the calculateArea method
    double calculateArea() const override {
        return 0.5 * base * height;
    }
};

// Function using polymorphism to calculate and display the area of any shape
void displayArea(const Shape& shape) {
    double area = shape.calculateArea();
    std::cout << "Area: " << area << std::endl;
}

int main() {
    Rectangle myRectangle(5.0, 3.0);
    Triangle myTriangle(4.0, 6.0);

    displayArea(myRectangle);
    displayArea(myTriangle);

    return 0;
}

Virtual Functions

Virtual functions enable polymorphism, allowing derived classes to provide their own implementation of a function declared in a base class.

virtual double calculateArea() const {
    return 0.0; // Default implementation for the base class
}

As you’ve seen in the previous code example, calculateArea is a virtual function from the base class.

Pure Virutal Functions

A pure virtual function in C++ is a virtual function declared in a base class that has no implementation in the base class and is meant to be overridden by derived classes. A class containing one or more pure virtual functions is called an abstract class, and you cannot create an instance of an abstract class.

// Abstract base class (parent class) with a pure virtual function
class Shape {
public:
    // Pure virtual function for calculating area
    virtual double calculateArea() const = 0;

    // Non-virtual function
    void displayShapeInfo() const {
        std::cout << "This is a shape." << std::endl;
    }
};

Friend Functions

A friend function is a function that is not a member of a class but has access to its private and protected members. Friend functions are declared inside the class with the friend keyword.

#include <iostream>

// Forward declaration of the class
class Rectangle;

// Friend function declaration
void displayDimensions(const Rectangle& rect);

class Rectangle {
private:
    double length;
    double width;

public:
    Rectangle(double len, double wid) : length(len), width(wid) {}

    // Friend function is declared inside the class
    friend void displayDimensions(const Rectangle& rect);
};

// Friend function definition
void displayDimensions(const Rectangle& rect) {
    // Accessing private members of Rectangle class
    std::cout << "Length: " << rect.length << ", Width: " << rect.width << std::endl;
}

int main() {
    Rectangle myRectangle(5.0, 3.0);

    // Calling the friend function
    displayDimensions(myRectangle);

    return 0;
}

Code Challenge

Create a simple program to manage a book inventory. Define two classes, Book and InventoryManager.

Loading...
> code result goes here
Prev
Next