CLOSE

What are Classes and Objects?

Definition: A class is a user-defined data type that serves as a blueprint for creating objects. It encapsulates data (attributes) and methods (behaviors) related to a specific entity. An object, on the other hand, is an instance of a class, representing a unique entity with its own state and behavior.

A class is a blueprint or template for creating objects. It is the logical representation that defines a set of attributes (data) and methods (functions) that the objects created from the class will have. A class does not occupy memory on its own. It's essentially a definition or a structure from which individual objects are instantiated.

For example, consider the following code snippet representing an Employee class:

#include <bits/stdc++.h>
using namespace std;

class Employee {
private:
    int salary; // to store the salary of employee

public:
    string employeeName; // to store the name of employee

    // Method to set the employee name
    void setName(string s) {
        employeeName = s;
    }

    // Method to set the salary
    void setSalary(int val) {
        salary = val;
    }

    // Method to get the salary
    int getSalary() {
        return salary;
    }
};
  • The Employee class acts as a blueprint that has the set of attributes and methods defined in it providing a logical meaning to a real-world entity employee.
  • The Employee class has a set of attributes (employeeName and salary) and set of methods (functions like setName, setSalary, getSalary) providing different functionality.

Defining Classes in C++

Syntax: In C++, classes are defined using the class keyword followed by the class name and a pair of curly braces enclosing the class definition.

Example:

class Rectangle {
private:
    double length;
    double width;
public:
    // Member functions declaration
    double calculateArea();
    double calculatePerimeter();
};

Attributes and Behaviors

Imagine a real “Dog” object:

  • Attributes: name, breed, color, age
  • Behaviors: bark(), eat(), sleep(), fetch()

So, you can think of an object as:

Object = Attributes (what it has) + Behaviors (what it does)

Attributes | Properties | Fields

Attributes (also called properties or fields) are the data or characteristics of an object. They represent the state of the object at any given moment. Attributes are typically defined within a class and can hold different types of information related to the object.

  • Think of them as characteristics or state of an object

For example, in the Rectangle class, there are two attributes: length and width.

Behaviors | Methods | Functions

Behaviors (also called methods or functions) are the actions or operations that an object can perform. Behaviors are implemented in methods and represent the functionality of the object.

  • They define how the object interacts with its environment or other objects.

For example, In the Rectange class, there are two behaviors/methods: calculateArea() and calculatePerimeter().

Creation of an Object

An object is an instance of a class. When an object is created from a class, memory is allocated for it, and it holds the data as specified by the class. An object interacts with other parts of the program, and methods can be called and attributes accessed that belong to it.

For example, Consider the following code snippet demonstrating the creation of objects from the Employee class:

#include <bits/stdc++.h>
int main() {
    // Creating an object of Employee class
    Employee obj1;

    // Setting different attributes of object 1 using available methods
    obj1.setName("Ajay"); // Set name to "Ajay"
    obj1.setSalary(10000); // Set salary to 10,000

    // Creating another object of Employee class
    Employee obj2;

    // Setting different attributes of object 2 in a similar way
    obj2.setName("Rahul"); // Set name to "Rahul"
    obj2.setSalary(15000); // Set salary to 15,000

    // Accessing the attributes of different objects
    cout << "Salary of " << obj1.employeeName << " is " << obj1.getSalary() << endl;
    cout << "Salary of " << obj2.employeeName << " is " << obj2.getSalary() << endl;

    return 0;
}
  • The class by itself doesn't take any memory. It is the object that takes up the memory once initialized.
  • The two objects (obj1 and obj2) have separate memory allocated for them in the program though they have the same attributes and methods. Because of this reason, an object cannot access the attributes and methods of any other object and vice-versa.

Instantiation: Objects of a class are created using the class name followed by parentheses, similar to calling a function.

Example:

Rectangle myRectangle; // Creating an object of the Rectangle class

Difference between Rectangle myRectangle and Rectangle myRectangle = new Rectangle;

1 Rectangle myRectangle;

  • This syntax creates an object of the Rectangle class using stack memory allocation.
  • The object is created directly on the stack, and its memory is automatically managed by the program.
  • No dynamic memory allocation is involved, and the object's lifetime is tied to the scope in which it is declared.
  • This syntax is suitable for creating objects with automatic storage duration, meaning they are automatically destroyed when they go out of scope.
Rectangle myRectangle; // Object created on the stack

2 Rectangle *myRectangle = new Rectangle;

  • This syntax creates an object of the Rectangle class using heap memory allocation.
  • This line declares a pointer variable named myRectangle of type Rectangle*, which is a pointer to an object of type Rectangle.
  • The new keyword is used to allocate memory dynamically on the heap, and it returns a pointer to the allocated memory.
  • The object is created on the heap, and its memory must be manually managed by the programmer using delete to deallocate it when it's no longer needed.
  • Objects created with dynamic memory allocation have a potentially longer lifetime and can exist beyond the scope in which they are created.
Rectangle *myRectangle = new Rectangle; // Object created on the heap

Accessing Members

Data Members: The data members (attributes) of an object can be accessed and modified using the dot (.) operator.
Member Functions: Similarly, member functions (methods) of an object can be invoked using the dot (.) operator.

Example:

myRectangle.length = 5.0;
myRectangle.width = 3.0;
double area = myRectangle.calculateArea();

Constructor and Destructor

Constructor: Constructors are special member functions that initialize the object's state when it is created. They have the same name as the class and no return type.
Destructor: Destructors are special member functions that are called when an object is destroyed. They clean up resources allocated by the object.

Example:

class Rectangle {
public:
    // Constructor
    Rectangle(double len, double wid) {
        length = len;
        width = wid;
    }
    // Destructor
    ~Rectangle() {
        // Cleanup code
    }
};

Encapsulation and Access Specifiers

Encapsulation: Encapsulation is the bundling of data and methods within a class, hiding the internal implementation details from the outside world.
Access Specifiers: C++ provides three access specifiers (public, private, and protected) to control the access to class members.

Example:

class Rectangle {
private:
    double length;
    double width;
public:
    // Member functions declaration
    double calculateArea();
    double calculatePerimeter();
};