C++ Classes and Objects


Introduction

In C++, classes and objects are fundamental concepts of Object-Oriented Programming (OOP). A class is a blueprint or template for creating objects, which are instances of the class. Objects encapsulate data and behaviors, making code modular, reusable, and easier to maintain.


1. What is a Class?

A class in C++ is a user-defined data type that holds data members (variables) and member functions (methods) together. It serves as a blueprint for creating objects. A class can also include constructors, destructors, and access modifiers like public, private, and protected.

Syntax for Defining a Class:

class ClassName {
    // Data members (variables)
    data_type member1;
    data_type member2;
    
    // Member functions (methods)
    return_type functionName() {
        // function body
    }
};
  • ClassName: The name of the class.
  • Data members: Variables that hold data related to the class.
  • Member functions: Functions that operate on the data members of the class.

2. What is an Object?

An object is an instance of a class. Once a class is defined, you can create objects based on that class, which hold specific values for the data members and can call the member functions.

To create an object, simply use the class name followed by the object name:

ClassName objectName;

You can create multiple objects of the same class, each holding its own data.


3. Example: Defining a Simple Class and Creating Objects

Let’s define a simple class Person with data members name and age, and a member function displayInfo() to print the details of the person.

Example 1: Basic Class and Object Definition

#include <iostream>
using namespace std;

// Define a class named Person
class Person {
public:
    string name;
    int age;

    // Member function to display information
    void displayInfo() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

int main() {
    // Create an object of the class Person
    Person person1;

    // Assign values to the object’s data members
    person1.name = "Alice";
    person1.age = 30;

    // Call the member function using the object
    person1.displayInfo();

    return 0;
}

Output:

Name: Alice
Age: 30

Explanation:

  • The class Person is defined with two data members: name and age, and one member function displayInfo().
  • In the main() function, an object person1 is created from the Person class.
  • The object’s data members are accessed and modified directly, and the displayInfo() function is called to print the values.

4. Constructors in C++

A constructor is a special member function that is automatically called when an object of a class is created. It is used to initialize the object’s data members. Constructors have the same name as the class and do not have a return type.

There are two types of constructors:

  • Default constructor: A constructor that takes no parameters.
  • Parameterized constructor: A constructor that takes parameters to initialize the object with specific values.

Example 2: Constructor in a Class

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    // Default constructor
    Person() {
        name = "Unknown";
        age = 0;
    }

    // Parameterized constructor
    Person(string n, int a) {
        name = n;
        age = a;
    }

    void displayInfo() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

int main() {
    // Create an object using the default constructor
    Person person1;
    person1.displayInfo();

    cout << endl;

    // Create an object using the parameterized constructor
    Person person2("Bob", 25);
    person2.displayInfo();

    return 0;
}

Output:

Name: Unknown
Age: 0

Name: Bob
Age: 25

Explanation:

  • The Person class has both a default constructor and a parameterized constructor.
  • The default constructor initializes the object’s members with default values ("Unknown" for name and 0 for age).
  • The parameterized constructor initializes the object with values passed as arguments.

5. Destructors in C++

A destructor is a special member function that is automatically called when an object is destroyed. It is used to clean up or release resources that the object may have acquired during its lifetime. Destructors have the same name as the class but are preceded by a tilde (~).

Example 3: Destructor in a Class

#include <iostream>
using namespace std;

class Person {
public:
    string name;

    // Constructor
    Person(string n) {
        name = n;
        cout << name << " has been created!" << endl;
    }

    // Destructor
    ~Person() {
        cout << name << " has been destroyed!" << endl;
    }
};

int main() {
    // Create an object of the Person class
    Person person1("Alice");

    // Destructor will be called automatically when person1 goes out of scope
    return 0;
}

Output:

Alice has been created!
Alice has been destroyed!

Explanation:

  • The constructor initializes the name of the Person object and prints a message when the object is created.
  • The destructor prints a message when the object is destroyed (automatically called when the object goes out of scope).

6. Access Specifiers in C++ Classes

C++ provides three access specifiers to control the accessibility of class members:

  • public: Members declared as public can be accessed from outside the class.
  • private: Members declared as private cannot be accessed from outside the class. They are only accessible from member functions of the class.
  • protected: Members declared as protected are similar to private, but they can be accessed in derived classes.

By default, members of a class are private if no access specifier is provided.

Example 4: Using Access Specifiers

#include <iostream>
using namespace std;

class Person {
private:
    string name;  // Private member
    int age;      // Private member

public:
    // Setter function (to access private members)
    void setDetails(string n, int a) {
        name = n;
        age = a;
    }

    // Getter function (to access private members)
    void displayInfo() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

int main() {
    Person person1;

    // Using setter function to access private members
    person1.setDetails("Charlie", 28);

    // Using getter function to display information
    person1.displayInfo();

    return 0;
}

Output:

Name: Charlie
Age: 28

Explanation:

  • The name and age data members are private, meaning they cannot be accessed directly outside the class.
  • To modify and access these private members, we use setter (setDetails()) and getter (displayInfo()) member functions.