Classes and Structures in C++

0
315

Introduction

C++ is a powerful and versatile programming language that supports both procedural and object-oriented programming paradigms. One of the key features of C++ is its ability to define and use classes and structures, which are fundamental building blocks of object-oriented programming. In this comprehensive guide, we will delve into the world of classes and structures in C++, exploring their definitions, differences, and practical examples.

Understanding Classes

Definition of Classes

In C++, a class is a user-defined data type that encapsulates data and the operations that can be performed on that data. It serves as a blueprint for creating objects, which are instances of the class. Let’s start by looking at a simple class definition:

#include <iostream>

class Car {
public:
    // Data members
    std::string brand;
    int year;

    // Member functions
    void displayInfo() {
        std::cout << "Brand: " << brand << ", Year: " << year << std::endl;
    }
};

In this example, Car is a class that has two data members (brand and year) and one member function (displayInfo). The public: keyword indicates that the members following it are accessible outside the class.

Creating Objects

Once a class is defined, you can create objects of that class. Objects are instances of the class and represent specific entities. For instance:

int main() {
    // Creating objects of the Car class
    Car myCar;
    myCar.brand = "Toyota";
    myCar.year = 2020;

    // Using the member function to display information
    myCar.displayInfo();

    return 0;
}

This program creates an instance of the Car class named myCar and sets its brand and year attributes. The displayInfo function is then called to output information about the car.

Access Specifiers

In C++, access specifiers (public, private, and protected) determine the visibility of class members. The public members are accessible from outside the class, while private members are only accessible within the class. The protected specifier is similar to private but allows access in derived classes.

class Example {
public:
    int publicVar;

private:
    int privateVar;

protected:
    int protectedVar;
};

Constructors and Destructors

Constructors are special member functions that are called when an object is created. They initialize the object’s state. In contrast, destructors are called when an object is about to be destroyed, allowing for cleanup activities.

class Rectangle {
public:
    // Constructor
    Rectangle(int l, int w) : length(l), width(w) {
        std::cout << "Rectangle created." << std::endl;
    }

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

    void displayArea() {
        std::cout << "Area: " << length * width << std::endl;
    }

private:
    int length;
    int width;
};

int main() {
    // Creating a Rectangle object
    Rectangle myRectangle(5, 8);

    // Using the member function to display the area
    myRectangle.displayArea();

    return 0;
}

In this example, the Rectangle class has a constructor that takes two parameters (length and width). The constructor initializes the private data members, and the destructor prints a message when the object is destroyed.

Understanding Structures

Definition of Structures

In C++, structures are similar to classes but have some key differences. While classes support access specifiers and can have member functions, structures are primarily used for grouping related data.

struct Point {
    int x;
    int y;
};

In this example, Point is a structure with two members (x and y). Unlike classes, the members of a structure are public by default.

Creating Structure Instances

Creating instances of structures is similar to creating instances of classes. You can define a structure and then create variables of that structure type.

int main() {
    // Creating a Point structure
    Point p1;
    p1.x = 3;
    p1.y = 7;

    // Accessing structure members
    std::cout << "Coordinates: (" << p1.x << ", " << p1.y << ")" << std::endl;

    return 0;
}

Differences Between Classes and Structures

While classes and structures share many similarities, there are notable differences:

  • Access Specifiers: In classes, members are private by default, whereas in structures, members are public by default.
  • Member Functions: Classes support member functions, allowing for encapsulation of behavior.
  • Inheritance: Classes support inheritance, allowing one class to inherit the properties and behaviors of another. Structures don’t support inheritance.

Practical Examples

Class Inheritance

One of the powerful features of classes in C++ is inheritance. Let’s consider an example involving a base class Shape and two derived classes Circle and Rectangle.

class Shape {
public:
    virtual double area() const = 0; // Pure virtual function
    virtual void display() const = 0;
};

class Circle : public Shape {
private:
    double radius;

public:
    Circle(double r) : radius(r) {}

    double area() const override {
        return 3.14 * radius * radius;
    }

    void display() const override {
        std::cout << "Circle - Radius: " << radius << ", Area: " << area() << std::endl;
    }
};

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

public:
    Rectangle(double l, double w) : length(l), width(w) {}

    double area() const override {
        return length * width;
    }

    void display() const override {
        std::cout << "Rectangle - Length: " << length << ", Width: " << width << ", Area: " << area() << std::endl;
    }
};

int main() {
    Circle myCircle(5.0);
    Rectangle myRectangle(4.0, 6.0);

    myCircle.display();
    myRectangle.display();

    return 0;
}

In this example, the Shape class is an abstract base class with pure virtual functions. The Circle and Rectangle classes inherit from Shape and provide their implementations for the area and display functions.

Structure for Employee Records

Let’s consider a scenario where we need to store employee records using a structure:

struct Employee {
    int employeeID;
    std::string name;
    double salary;
};

void displayEmployee(const Employee& emp) {
    std::cout << "Employee ID: " << emp.employeeID << ", Name: " << emp.name << ",

 Salary: $" << emp.salary << std::endl;
}

int main() {
    Employee emp1 = {101, "John Doe", 50000.0};
    Employee emp2 = {102, "Jane Smith", 60000.0};

    displayEmployee(emp1);
    displayEmployee(emp2);

    return 0;
}

In this example, the Employee structure is used to represent employee records. The displayEmployee function takes an Employee as a parameter and prints the information.

Conclusion

In this extensive guide, we’ve explored the concepts of classes and structures in C++. Classes provide a mechanism for encapsulating data and behavior, supporting features like access specifiers, constructors, and inheritance.

Understanding the differences and applications of classes and structures is crucial for effective C++ programming. By leveraging these features, developers can design modular, maintainable, and scalable software systems. Whether you’re building complex class hierarchies or organizing simple data structures, the principles covered in this guide serve as a solid foundation for mastering object-oriented programming in C++.

Read More –

Search an element in a Linked List – https://kamleshsingad.com/search-an-element-in-a-linked-list/

Find the Length of a Linked List – https://kamleshsingad.com/find-the-length-of-a-linked-list/

Convert an array to a Linked List – https://kamleshsingad.com/convert-an-array-to-a-linked-list/

LEAVE A REPLY

Please enter your comment!
Please enter your name here