Classes and Objects in C++
Updated on 10th Jan, 24 9.2K Views

In this blog, we will go through the basics of classes and objects in C++, covering what they are, what an object is, storage classes, virtual classes, and class scope. You will thoroughly understand the fundamentals of “What Is Class in C++” and its use by the end of this article.

Check out our YouTube video on C programming language for the absolute beginners

Introduction to Class in C++

Introduction to Class in C++

A class in C++ is a user-defined data type that enables you to group together data and methods associated with that data. In essence, it serves as a template for producing objects that are instances of the class.

The two basic components of a class are data members and member functions. Members of a data structure are variables that contain data, and member functions are operations on that data. A class’s data and functions are “encapsulated” or kept separate and off-limits to other program elements. This encapsulation offers data security and aids in preventing unintentional data change.

Here’s an example of a simple class in C++

#include <iostream>
using namespace std;
class Person {
  private:
    std::string name;
    int age;
  public:
    Person(std::string n = "", int a = 0) {
      name = n;
      age = a;
    }
    std::string getName() const {
      return name;
    }
    void setName(const std::string& n) {
      name = n;
    }
    int getAge() const {
      return age;
    }
    void setAge(int a) {
      age = a;
    }
};
int main() {
  Person person("Peter Doe", 30);
  std::cout << "Name: " << person.getName() << std::endl;
  std::cout << "Age: " << person.getAge() << std::endl;
  return 0;
}

In this example, the Person class has data members for “name” and “age”, as well as member functions for setting and getting those data members. The “private” keyword indicates that these data members are only accessible within the class itself and cannot be accessed from outside the class.

Want to jumpstart your career in Computer Programing? Enrol in our C Programming Course and gain your skills to succeed!

What is an Object in C++

A key idea in object-oriented programming is the concept of objects, which lets you construct many class instances, each with its own set of data and functions. You may store and modify data in an organized and structured manner and write more flexible and reusable code by creating class objects.

An object in C++ is a particular instance of a class. It is generated using the class’s constructor function and, aside from having its own set of data and functions, is just a duplicate of the class.

Using the Person class’s previous example, here is how to build a Person class object.

Person p1; // Creates an object of the Person class

In this example, we use the default constructor function to create an object of the Person class. Following object creation, we can use the dot (.) operator to access its data members and member functions, as shown in this.

p1.setName("Peter"); // Sets the name of the Person object to "Peter"
p1.setAge(30); // Sets the age of the Person object to 30

std::cout << p1.getName() << " is " << p1.getAge() << " years old." << std::endl; // Outputs "Peter is 30 years old."

In this example, we set the p1 object’s data members using the setName() and setAge() functions, and we get and report the data using the getName() and getAge() functions.

Check out our blog on What is Friend Function in C++? to learn more about C++ and its functions.

Get 100% Hike!

Master Most in Demand Skills Now !

Types of Class in C++

Types of Class in C++

Classes are a crucial component of the C++ programming language. You can use them to organize your code, build intricate data kinds, and more. There are differences between each class, though. This thorough introduction will examine the many class kinds in C++, including friend classes, abstract classes, concrete classes, and more. 

  • Standard classes These are the fundamental classes the C++ programming language offers, including string, vector, and map.
  • Abstract classes Classes that serve as the base for additional classes are known as abstract classes because they cannot be instantiated on their own. They often contain one or more pure virtual functions, which any derived class must implement.
  • Concrete classes – These are self-initiating classes and offer full implementations of all the member functions they contain.
  • Derived classes – Derived classes are classes that add their own member variables and functions while inheriting from a base class.
  • Template classes – Classes that work with different types thanks to the use of one or more template parameters are known as template classes.
  • Friend classes – These are classes that, despite not belonging to the class in question, have access to its private members.
  • Nested classes – Nested classes are those defined inside another class and have access to its private members. They may be non-static or static.

Learn what a Linear Data Structure is and how it works!

Structure of a Class

Structure of a Class

Any programmer who wants to write compelling and reliable code must understand the C++ class structure. You can create and use object-oriented programs more effectively if you know the data members, member functions, access specifiers, constructors, and destructors.

  • Members of a Class – Data members and member functions comprise the two primary components of a Class in C++. Members are functions that belong to the class, whereas data members are variables that store data inside the class.
  • Data Members – Data members may be of any type, including strings, floats, and integers. The class declares them, and the member functions can use them. Since each object in a class has a unique set of data members, data members are also known as instance variables.
  • Member Functions – Member functions are those that belong to the class. The data members of the class are accessible to them, and they can alter it. Two sorts of member functions are member functions that affect the class’s data members and member functions that do not.
  • Access Specifiers – Determine the accessibility of the class’s data members and member functions using access specifiers. In C++, there are three access specifiers: protected, private, and public.
    • Public – Public data members and member functions can be accessed from outside the class.
    • Private – Private data members and member functions can only be accessed from within the class.
    • Protected – Protected data members and member functions can be accessed by the class and its derived classes.
  • Constructors and Destructors – Special member functions called constructors and destroyers are used to create and deconstruct class objects, respectively. When an object of the class is created, a constructor is called, and when an object of the class is destroyed, a destructor is invoked. The data members of a class are initialized using constructors, and any resources the class has allocated are released using destructors.

Check out C and Data Structure Interview Questions to crack your next interview!

Constructors and Destructors

When an object of a class is formed in C++, its constructor is a particular member function that is called. Initializing the object’s data members and carrying out any additional setup that might be required are both done using it.

Here’s an example of a constructor for the Person class

#include <iostream> 
using namespace std;  
// define a new class called Person
class Person {
  private:  // member variables and functions below are private
 std::string name;  // define a private string member variable called name
    int age; // define a private integer member variable called age
  public:  // member functions below are public
 // define a public constructor that takes a string argument n and an integer argument a
    Person(std::string n, int a) {
        name = n;  
        age = a;   
    }
// define a public member function that returns the name member variable
    std::string getName() const {
        return name;
    }
// define a public member function that returns the age member variable
    int getAge() const {
        return age;
    }
};
int main() {
  Person p("Peter", 30);  // create a new Person object with name "Peter" and age 30
  std::cout << "Name: " << p.getName() << std::endl;
  // print the name using getName() function
  std::cout << "Age: " << p.getAge() << std::endl;
    // print the age using getAge() function
  return 0;  // return 0 to indicate successful program termination
}

In this example, we have defined a constructor for the Person class that takes two parameters, “n” for name and “a” for age. The constructor initializes the “name” and “age” data members of the object using these parameters. 

To create an object of the Person class using this constructor, we would do the following.

Person p("Peter", 30); // Creates a Person object with name "Peter" and age 30

In this example, we use the constructor that accepts two parameters to build an object of a Person named “p”. The constructor sets the object’s “name” and “age” data members to, respectively, “Peter” and 30.

C++ also features destructors in addition to constructors. When an object belonging to a class is destroyed, a destructor, a particular member function of that class, is invoked. It is employed to remove any resources that the object may have accumulated during its existence.

Here’s an example of a destructor for the Person class:

#include <iostream>
using namespace std; 
class Person { // define a Person class
  private: // define private access specifier for class members
  std::string name; // define a private string data member named 'name'
    int age; // define a private integer data member named 'age'
  public: // define public access specifier for class members
    Person(std::string n, int a) { // define a constructor for Person class that takes a string and an integer as arguments
    name = n; // set the value of 'name' data member to the argument passed in
   age = a; // set the value of 'age' data member to the argument passed in
    }
    ~Person() { // define a destructor for the Person class
        std::cout << "Person object destroyed." << std::endl; // print a message to the console
    }
    std::string getName() { // define a public member function named 'getName' that returns a string
        return name; // return the value of 'name' data member
    }
    int getAge() { // define a public member function named 'getAge' that returns an integer
        return age; // return the value of 'age' data member
    }
};
int main() { 
  Person p("Peter", 30); // create a Person object named 'p' with the arguments "Peter" and 30 passed to the constructor
  std::cout << "Name: " << p.getName() << std::endl; // print the name of the Person object to the console
  std::cout << "Age: " << p.getAge() << std::endl; // print the age of the Person object to the console
  return 0; // return 0 to indicate successful program termination
}

In this example, we’ve created a destructor for the Person class that merely prints a message upon object destruction. 

We might let an object of the Person class exit the scope or actively delete it using the “delete” keyword. The object’s destructor is automatically triggered when it is destroyed.

{
    Person p("Peter", 30); // Creates a Person object with name "Peter" and age 30
} // p object is destroyed when it goes out of scope

This example creates a Person object with the name “p” inside of a code block. The object is out of scope and destroyed after the code block, which causes the destructor to output a message.

Learn how to use Hamming Distance with our Hamming Distance blog.

Career Transition

Non-Tech to IT Associate | Career Transformation | AWS Certification Course - Intellipaat Reviews
Non Tech to DevOps Engineer Career Transition | Intellipaat Devops Training Reviews - Nitin
Upskilled & Got Job as Analyst After a Career Break |  Data Science Course Story - Shehzin Mulla
Successful Career Change after Completion of AWS Course - Krishnamohan | Intellipaat Review
Got Job Promotion After Completing Artificial Intelligence Course - Intellipaat Review | Gaurav
Intellipaat Reviews | Big Data Analytics Course | Career Transformation to Big Data | Gayathri

Conclusion

Class in C++ is a user-defined data type that encapsulates data and functions related to that data. It provides a blueprint for creating objects, which are class instances. Objects are created using the class’s constructor function and represent a copy of the class with its own set of data and functions

The structure of a class includes data members and member functions, which are encapsulated for data security. C++ also has constructors and destructors, which are special member functions of a class used to initialize and clean up objects properly.

Classes and objects are fundamental concepts in C++ and are used extensively in object-oriented programming to create more organized, modular, and flexible code.

Don’t miss out on the latest programming trends and advancements – be part of Intellipaat’s Community today!

Course Schedule

Name Date Details
Python Course 30 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 06 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 13 Apr 2024(Sat-Sun) Weekend Batch
View Details

Speak to our course Advisor Now !

Related Articles

Subscribe to our newsletter

Signup for our weekly newsletter to get the latest news, updates and amazing offers delivered directly in your inbox.