Classes and Objects in C++.

C++ is an object-oriented programming language, and one of its key features is the ability to create and use classes and objects. Classes and Objects in C++ are the basic building blocks for Object Oriented Programming. In this article, we are going to learn the concept of classes and objects in detail with real-life examples.


What is a Class?

At its core, a class is a blueprint for creating objects. It encapsulates data (attributes) and behaviors (methods), providing a logical structure for organizing and modeling real-world entities. 

Data Members (Attributes): Data members define the attributes of a class, representing its state. They can include fundamental types or other user-defined types.(alert-passed)
Member Functions (Methods): Member functions define the behaviors of a class. They encapsulate operations that can be performed on the class's data.(alert-passed)

SyntaxIn C++, declaring a class involves using the class keyword, followed by the class name and a set of curly braces containing class members.

class ClassName {
    Access Specifier:

    Data Member;

    Member Function();
};


Example: Let's understand with an example, a Car can be represented as a class. A Car class can have attributes (data members) that define its state and behaviors (member functions) that represent its actions. 

class Car {
public: //Access Specifier
    // Attributes
    string brand;
    string model;
    int year;
    bool engineRunning;

    // Member Function to Start the Engine
    void startEngine() {
        if (!engineRunning) {
            cout << "Starting the engine...\n";
            engineRunning = true;
        } else {
            cout << "The engine is already running.\n";
        }
    }
};

What is an Object?

Objects are instances of classes, representing tangible entities in a program. They encapsulate data and behaviors defined by the class, forming the building blocks of C++ applications.

Syntax: Creating an object involves specifying the class name followed by the object name.
ClassName objectName;  // Creating an object

The data member and member function of the class can be accessed using the dot operator with the object name. For example, if your object name is myCar and you want to access the member function startEngine() then you have to write myCar.startEngine() to access that particular function.

Access Specifiers in C++.

Access specifiers control the visibility of class members (data member and member function) from different parts of the program. They are keywords used to define the accessibility or visibility of class members (data members and member functions). 

There are three access specifiers in C++:
  • Public: Members declared as public are accessible from any part of the program. They have no restrictions on access.
  • Private: Members declared as private are only accessible within the same class. They are not accessible from outside the class.
  • Protected: Members declared as protected are similar to private members but have one additional feature: they can be accessed in the derived classes. They are not accessible from outside the class.
Example:
//Access Specifier Example
class AccessExample {
public:
    int publicVar;

private:
    int privateVar;

protected:
    int protectedVar;

public:
    void displayValues() {
        cout << "Public: " << publicVar << "\n";
        cout << "Private: " << privateVar << "\n"; //Err: private is not accessible
        cout << "Protected: " << protectedVar << "\n";
    }
};

Access specifiers provide control over the visibility and accessibility of the class members, contributing to the principles of encapsulation and data hiding in object-oriented programming.

Constructors.

In C++, a constructor is a special member function that is automatically called when an object is created. It has the same name as the class and does not have any return type. The purpose of a constructor is to initialize the object's data members or perform other setup operations when an object is created.

There are two main types of constructors:

Default Constructor:
  • A default constructor is a constructor that takes no parameters.
  • If a class does not have any constructor defined, the compiler automatically generates a default constructor.
  • It initializes the data members with default values (zero or null, depending on the data type).

Parameterized Constructor:
  • A parameterized constructor is a constructor that takes parameters.
  • It allows you to initialize the object with specific values when it is created.
Example:
#include <iostream>

class Car {
private:
    std::string brand;
    int year;

public:
    // Default Constructor
    Car() {
        brand = "Unknown";
        year = 0;
    }

    // Parameterized Constructor
    Car(std::string carBrand, int carYear) {
        brand = carBrand;
        year = carYear;
    }

    void displayInfo() {
        std::cout << "Brand: " << brand << "\n";
        std::cout << "Year: " << year << "\n";
    }
};

int main() {
    // Using Default Constructor
    Car defaultCar;
    defaultCar.displayInfo();

    // Using Parameterized Constructor
    Car customCar("Toyota", 2022);
    customCar.displayInfo();

    return 0;
}
Output:
Brand: Unknown
Year: 0
Brand: Toyota
Year: 2022

In this example, the Car class has a default constructor that initializes the brand and year with default values. It also has a parameterized constructor that allows you to specify the brand and year when creating an object.

Destructor.

In C++, a destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted using the delete keyword. The purpose of a destructor is to release resources or perform cleanup operations before the object is destroyed.

The destructor has the same name as the class, preceded by a tilde (~). Unlike constructors, destructors do not take any parameters, and a class can have only one destructor.

Example:
#include <iostream>

class MyClass {
public:
    // Constructor
    MyClass() {
        std::cout << "Constructor called\n";
    }

    // Destructor
    ~MyClass() {
        std::cout << "Destructor called\n";
    }
};

int main() {
    // Object creation
    MyClass obj; // Constructor called

    // Object goes out of scope
    // Destructor is automatically called here

    return 0;
}
Output:
Constructor called
Destructor called

I hope you understand the basic workings of classes and objects in Object Oriented Programming. There are several key points that you can keep in mind when you are working with classes. 
  • Use access specifiers (public, private, protected) to control the visibility of class members.
  • Always define a constructor and, if needed, a destructor to manage the object's lifecycle.
  • Ensure that all class members are properly initialized, either through default values, member initialization lists, or in the constructor body.
  • Consider making functions const-correct when they do not modify the object's state.
  • Access static members using the class name, not an instance.
  • Prefer composition over inheritance to achieve polymorphic behavior.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS