Classes and Objects

In C++, classes and objects are fundamental concepts used for creating user-defined data types. They provide a blueprint for creating objects, which are instances of a class.

Classes

A class acts as a blueprint or template that defines the properties (data) and behaviors (functions) of objects. Imagine a cookie cutter for creating cookies. The cutter (class) defines the overall shape (properties) of the cookie, but each cookie (object) can have its own unique details like frosting or sprinkles.

Members of a Class

Classes are composed of members, which can be:

Data Members (Member Variables): These variables store information specific to an object. They represent the object’s properties or state.

Member Functions: These functions define the actions or behaviors that objects of the class can perform.

				
					class Car {
public:
    std::string color;  // Data member (car's color)
    int year;          // Data member (car's model year)

    void startEngine() { // Member function (starts the engine)
        std::cout << "Engine started!" << std::endl;
    }
};

				
			

Creating Objects

Instantiating a Class: Creating Objects

Once you have a class definition (the blueprint), you can create objects (instances) of that class. Think of using the cookie cutter to create individual cookies from the dough.

				
					Car myCar; // Declares an object named myCar of class Car

myCar.color = "Red";   // Assigning value to a data member (car color)
myCar.year = 2024;     // Assigning value to a data member (car year)

myCar.startEngine();  // Calling a member function on the object

				
			

Accessing Object Members

Instantiating a Class: Creating Objects

Once you have a class definition (the blueprint), you can create objects (instances) of that class. Think of using the cookie cutter to create individual cookies from the dough.

				
					std::cout << "Car Color: " << myCar.color << std::endl;
std::cout << "Car Year: " << myCar.year << std::endl;

				
			

Classes and Objects Example

Let’s see how to declare a class and create objects in C++.

Syntax of Class Declaration

				
					#include <iostream>
#include <string>
using namespace std;

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

    // Member function
    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    // Creating objects of class Car
    Car car1, car2;

    // Assigning values to members
    car1.brand = "Toyota";
    car1.year = 2020;

    car2.brand = "Honda";
    car2.year = 2019;

    // Displaying object details
    car1.display();
    car2.display();

    return 0;
}

				
			
				
					// output //
Brand: Toyota, Year: 2020
Brand: Honda, Year: 2019

				
			

Explanation:

  • We defined a class Car with data members brand and year, and a member function display.
  • In the main function, we created two objects car1 and car2 of type Car.
  • We assigned values to the data members of each object.
  • Finally, we called the display function for each object to print their details.

Advanced Class Features

Access Specifiers: Controlling Member Visibility

  • C++ provides access specifiers (public, private, and protected) to control access to members within a class and its derived classes (covered later).
  • public members are accessible from anywhere in the program.
  • private members are only accessible within the class and its friend classes (if declared).
  • protected members are accessible within the class, its derived classes, and friend classes.
				
					#include <iostream>
#include <string>
using namespace std;

class MyClass {
public:
    int publicVar;

    // Constructor
    MyClass(int pv) {
        publicVar = pv;
    }

    // Public member function
    void publicFunction() {
        cout << "Inside public function" << endl;
    }

private:
    int privateVar;

    // Private member function
    void privateFunction() {
        cout << "Inside private function" << endl;
    }

protected:
    int protectedVar;

    // Protected member function
    void protectedFunction() {
        cout << "Inside protected function" << endl;
    }

public:
    // Friend function declaration
    friend void friendFunction(MyClass obj);
};

// Friend function definition
void friendFunction(MyClass obj) {
    cout << "Accessing private member from friend function: " << obj.privateVar << endl;
    cout << "Accessing protected member from friend function: " << obj.protectedVar << endl;
}

int main() {
    MyClass obj(10);

    // Accessing public member
    cout << "Public member: " << obj.publicVar << endl;
    obj.publicFunction();

    // Private and protected members cannot be accessed directly from outside the class
    // cout << "Private member: " << obj.privateVar << endl; // Compilation error
    // obj.privateFunction(); // Compilation error
    // cout << "Protected member: " << obj.protectedVar << endl; // Compilation error
    // obj.protectedFunction(); // Compilation error

    // Accessing private and protected members through friend function
    friendFunction(obj);

    return 0;
}

				
			
				
					// output //
Public member: 10
Inside public function
Accessing private member from friend function: 0
Accessing protected member from friend function: 0

				
			

Explanation:

  • We define a class MyClass with public, private, and protected members along with corresponding member functions.
  • In the main() function, we create an object obj of type MyClass and initialize it with a value.
  • We demonstrate the accessibility of public members by accessing publicVar and publicFunction() directly from the main() function.
  • Private and protected members cannot be accessed directly from outside the class. Hence, trying to access privateVar, privateFunction(), protectedVar, and protectedFunction() from the main() function results in compilation errors.
  • However, we demonstrate accessing private and protected members through a friend function friendFunction(), which has access to private and protected members of the class.
  • The friend function friendFunction() is declared and defined outside the class and provided access to private and protected members of MyClass.
  • Upon running the program, we can see the output displaying the values of private and protected members accessed through the friend function.

Lets more understand Protected ?

The protected access specifier in C++ provides a middle ground between public and private. Members declared as protected within a class are accessible to the class itself, its derived classes, and friend classes.

Access within the Class

Protected members can be accessed by member functions of the same class just like private members.

				
					class MyClass {
protected:
    int protectedVar;

public:
    void accessProtected() {
        protectedVar = 10; // Accessing protected member within the class
    }
};

				
			

Access within Derived Classes

Derived classes have access to protected members of their base class. This allows derived classes to inherit and use these members.

				
					class DerivedClass : public MyClass {
public:
    void accessProtectedFromDerived() {
        protectedVar = 20; // Accessing protected member from derived class
    }
};

				
			

Access within Friend Classes

Friend classes can access protected members of the class if they are declared as friends.

				
					class FriendClass {
public:
    void accessProtectedFromFriend(MyClass obj) {
        obj.protectedVar = 30; // Accessing protected member from friend class
    }
};

				
			

Complete Example

				
					#include <iostream>
using namespace std;

class MyClass {
protected:
    int protectedVar;

public:
    MyClass() {
        protectedVar = 0;
    }

    void accessProtected() {
        protectedVar = 10; // Accessing protected member within the class
    }
};

class DerivedClass : public MyClass {
public:
    void accessProtectedFromDerived() {
        protectedVar = 20; // Accessing protected member from derived class
    }
};

class FriendClass {
public:
    void accessProtectedFromFriend(MyClass obj) {
        obj.protectedVar = 30; // Accessing protected member from friend class
    }
};

int main() {
    MyClass obj;
    DerivedClass derivedObj;
    FriendClass friendObj;

    obj.accessProtected(); // Accessing protected member within the class

    derivedObj.accessProtectedFromDerived(); // Accessing protected member from derived class

    friendObj.accessProtectedFromFriend(obj); // Accessing protected member from friend class

    cout << "Value of protectedVar: " << obj.protectedVar << endl; // Output: 30

    return 0;
}

				
			
				
					// output //
Value of protectedVar: 30

				
			

Explanation:

  • We define a class MyClass with a protected member protectedVar.
  • The MyClass constructor initializes protectedVar to 0, and accessProtected() function modifies its value.
  • DerivedClass is derived from MyClass and has access to the protected member protectedVar.
  • FriendClass is a friend class of MyClass and can access protectedVar.
  • In the main() function, we create objects of MyClass, DerivedClass, and FriendClass.
  • We demonstrate accessing and modifying protectedVar from within MyClass, DerivedClass, and FriendClass.
  • Finally, we output the value of protectedVar to verify the changes made by the friend class.

Member Functions

Member functions are functions declared within a class and can access the class’s private and protected members.

				
					#include <iostream>
using namespace std;

// Defining a class with member functions
class Rectangle {
private:
    int length;
    int width;

public:
    void setDimensions(int l, int w) {
        length = l;
        width = w;
    }

    int calculateArea() {
        return length * width;
    }
};

int main() {
    Rectangle rect;

    // Setting dimensions of the rectangle
    rect.setDimensions(5, 10);

    // Calculating and printing area
    cout << "Area of the rectangle: " << rect.calculateArea() << endl;

    return 0;
}

				
			
				
					// output //
Area of the rectangle: 50

				
			

Explanation:

  • We defined a class Rectangle with private data members length and width, and two member functions setDimensions and calculateArea.
  • In the main function, we created an object rect of type Rectangle.
  • We called the setDimensions function to set the dimensions of the rectangle.
  • Then, we called the calculateArea function to calculate and print the area of the rectangle.

Constructors and Destructors

Constructors are special member functions that are automatically called when an object is created. Destructors are called when an object is destroyed.

Types of Constructors

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

Default Constructor

A default constructor is a constructor that is automatically called when an object is created without any arguments. If no constructor is defined explicitly, the compiler provides a default constructor.

Note – A default constructor is a constructor that takes no arguments.

				
					#include <iostream>
#include <string>
using namespace std;

class Person {
private:
    string name;
    int age;

public:
    // Default Constructor
    Person() {
        name = "Unknown";
        age = 0;
    }

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

int main() {
    // Creating an object using the default constructor
    Person person;

    // Displaying object details
    person.display();

    return 0;
}

				
			
				
					// output //
Name: Unknown, Age: 0

				
			

Explanation:

  • We defined a class Person with private data members name and age.
  • We provided a default constructor Person() which initializes the name with “Unknown” and age with 0.
  • In the main function, we created an object person of type Person using the default constructor.
  • We called the display function to print the details of the person object.

Parameterized Constructor

A parameterized constructor is a constructor that takes parameters to initialize the object with specific values.

Note – A parameterized constructor is a constructor that takes one or more parameters.

				
					#include <iostream>
#include <string>
using namespace std;

class Person {
private:
    string name;
    int age;

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

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

int main() {
    // Creating an object using the parameterized constructor
    Person person("Alice", 25);

    // Displaying object details
    person.display();

    return 0;
}

				
			
				
					// output //
Name: Alice, Age: 25

				
			

Explanation:

  • We defined a class Person with private data members name and age.
  • We provided a parameterized constructor Person(string n, int a) which takes a name and an age to initialize the object.
  • In the main function, we created an object person of type Person using the parameterized constructor and passed values “Alice” and 25.
  • We called the display function to print the details of the person object.

Copy Constructor

A copy constructor is a constructor that initializes an object by copying the values of another object of the same class.

Note – A copy constructor is a constructor that takes a reference to an object of the same class and initializes a new object with the same values.

				
					#include <iostream>
#include <string>
using namespace std;

class Person {
private:
    string name;
    int age;

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

    // Copy Constructor
    Person(const Person &p) {
        name = p.name;
        age = p.age;
    }

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

int main() {
    // Creating an object using the parameterized constructor
    Person person1("Alice", 25);

    // Creating another object using the copy constructor
    Person person2 = person1;

    // Displaying object details
    person1.display();
    person2.display();

    return 0;
}

				
			
				
					// output //
Name: Alice, Age: 25
Name: Alice, Age: 25

				
			

Explanation:

  • We defined a class Person with private data members name and age.
  • We provided a parameterized constructor Person(string n, int a) to initialize the object with a name and an age.
  • We also provided a copy constructor Person(const Person &p) which takes a reference to another Person object and copies its values.
  • In the main function, we created an object person1 using the parameterized constructor.
  • We created another object person2 using the copy constructor and passed person1 as an argument.
  • We displayed the details of both objects.

Destructors

Explanation:

  • We defined a class Person with private data members name and age.
  • We provided a parameterized constructor Person(string n, int a) to initialize the object with a name and an age.
  • We also provided a copy constructor Person(const Person &p) which takes a reference to another Person object and copies its values.
  • In the main function, we created an object person1 using the parameterized constructor.
  • We created another object person2 using the copy constructor and passed person1 as an argument.
  • We displayed the details of both objects.
				
					#include <iostream>
#include <string>
using namespace std;

// Defining a class with constructor and destructor
class Book {
private:
    string title;
    string author;

public:
    // Parameterized Constructor
    Book(string t, string a) {
        title = t;
        author = a;
        cout << "Book object created" << endl;
    }

    // Destructor
    ~Book() {
        cout << "Book object destroyed" << endl;
    }

    void display() {
        cout << "Title: " << title << ", Author: " << author << endl;
    }
};

int main() {
    // Creating an object of class Book
    Book book("The Great Gatsby", "F. Scott Fitzgerald");

    // Calling the display function
    book.display();

    return 0;
}

				
			
				
					// output //
Book object created
Title: The Great Gatsby, Author: F. Scott Fitzgerald
Book object destroyed

				
			

Explanation:

  • We defined a class Book with private data members title and author, a parameterized constructor, a destructor, and a member function display.
  • In the main function, we created an object book of type Book by passing values to the constructor.
  • The constructor prints a message when the object is created.
  • The display function prints the details of the book.
  • When the program ends, the destructor is automatically called, printing a message indicating the destruction of the object.

Key Takeaways

  • Classes act as blueprints that define the properties (data members) and behaviors (member functions) of objects.
  • Objects are instances of a class, representing real-world or abstract entities with specific data and functionalities.
  • Access specifiers (publicprivateprotected) control member visibility within a class and its derived classes.
  • Constructors and destructors are special member functions that manage object creation and destruction, respectively.

Classes and objects in C++ provide a powerful mechanism for organizing and manipulating data. By encapsulating data and functions into classes, we can build modular and reusable code. Understanding these concepts is essential for writing efficient and maintainable C++ programs. Keep practicing and experimenting to master classes and objects in C++. Happy coding !❤️

Table of Contents