Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
C++ Classes
3.
C++ Object
4.
Creating a Class and Declaring Objects
4.1.
Declaring Objects
5.
Access Specifier
5.1.
Public
5.2.
C++
5.3.
Private
5.4.
C++
5.5.
Protected
5.6.
C++
6.
Member Functions in Classes
6.1.
Outside Class
6.2.
Inside Class
7.
Constructors in C++
7.1.
Implementation
7.2.
C++
7.3.
 
8.
Destructors in C++
8.1.
Implementation
8.2.
C++
9.
Frequently Asked Questions
9.1.
What are classes and objects in C++?
9.2.
How many objects in a class?
9.3.
Why do we need classes?
9.4.
What is object class type?
10.
Conclusion
Last Updated: Jul 4, 2024
Easy

C++ Classes and Objects

Introduction

C++ is an object-oriented programming language where classes and objects are fundamental components. Classes, the building blocks of C++, are user-defined data types that serve as blueprints for creating objects. Each class contains its own data members and member functions, which can be accessed through instances of that class. This concept is central to understanding C++ Classes and Objects.

C++ Classes and Objects

For example: Consider a class of students. There can be many students, but all of them will share some common properties like all of them will have a name, age, marks, roll no. So a student is a class having name, age, marks, roll no as its properties.

C++ Classes

C++ classes are user-defined data types that serve as a blueprint for creating objects. It consists of data members, which are data variables, and member functions, which are functions used to manipulate these variables. Together, data members and member functions define the behavior and properties of the objects created from the class.

For example, in a class named Student, the data members might include name, roll_no, age, and marks. The member functions could include updateMarks(), getAge(), and so on.

C++ Object

C++ objects are any real-world entity, such as a chair, pencil, or eraser. It is defined as an entity that has both state and behavior and is an instance of a class. When a class is defined, no memory is initially allocated. However, memory is allocated when an object of that class is created.

For example: if two objects naming student-1 and student-2 of Student class are created, then both of them will have separate memory allocated to them, both of them will have all the properties of the Student class.

Creating a Class and Declaring Objects

In order to define a class in C++, the ‘class’ keyword must be used, followed by the className. The data members and member functions which constitute the body of the class are defined inside curly brackets. A class is always terminated by a semicolon at the end.

class className
{
     Access specifier // can be private, protected, public
     Data members  // variables 
     Member Functions() // methods to access data members
}; // Class ends with a semicolon

Declaring Objects

When a class is defined, only the specifications or the blueprint for the object is defined, no memory is allocated. In order to use the data and access the functions defined inside a class, we need an object. In order to access the data members and member functions of a class, the dot (‘.’) operator is used along with the object name. For example, if student1 is the object name and we want to access the getMarks() member function, we will write student1.getMarks() .

Syntax

className objectName;

Access Specifier

Access Specifiers are used to implement data hiding which is a very important aspect of object-oriented programming. Access Specifiers in a class are used to assign the accessibility to the class members, that is, they are used to set some level of restrictions on the class members as to not get directly accessible from outside the function. There are 3 types of access specifiers:

Public

  • All the class members declared under this are available to everyone, that is, they can be accessed by other classes and functions too. The public members are directly accessible using the dot operator with the object of the class from anywhere in the program.

 

Example

  • C++

C++

#include<iostream>
using namespace std;

class student{
  public:
int marks;

int getPercentage()
{
return (marks*100)/100;
}
};

int main(){
 
  student student1;
  student1.marks=92;
cout<<"Percentage = "<<student1.getPercentage()<<endl;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Percentage = 92

 

You practice by yourself with the help of online c++ compiler.

Private

  • All the class members declared under private can be accessed only by the member functions inside the class, they can not be accessed by any object or function outside the class. The member functions and the friend functions are allowed to access them.
  • If we don't specify any access modifiers for the members inside the class, then by default, the access modifier for members is set as Private. 

 

Example

#include<iostream>
using namespace std;

class student{
    private:
        int marks;
     public:
        int getPercentage()
        {
            return (marks*100)/100;
        }
};

int main(){
   
   student student1;
   student1.marks=92;
   cout<<"Percentage = "<<student1.getPercentage()<<endl;
}

 

Output

18:13: error: 'marks' is a private member of 'student'
   student1.marks=92;
            ^
r-6:13: note: declared private here
        int marks;
            ^

 

The above program gives a compile-time error as we are not allowed to access the private data members of a class directly from outside the class.

We can indirectly access the private data members using the public member functions of the class.

Example

  • C++

C++

#include<iostream>
using namespace std;

class student{
private:
int marks;
  public:
int getPercentage(int m)
{
marks=m;
return (marks*100)/100;
}
};

int main(){
 
  student student1;
cout<<"Percentage = "<<student1.getPercentage(92)<<endl;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Percentage = 92

 

Protected

  • All the data members which are declared under this cant be accessed outside of the class unless with the help of a friend class. The only difference between private and protected is that protected class members can not be accessed by any subclass of that class as well.

 

Example

  • C++

C++

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

// base class
class Database{ 
// protected data members
protected:
int marks;
};

// sub class or derived class from public base class
class student : public Database
{
public:
void setMarks(int m)
{
marks = m; 
}
 
void displayMarks()
{
cout << "Marks = " << marks << endl;
}
};

// main function
int main() {

student obj1;
obj1.setMarks(81);
obj1.displayMarks();

}
You can also try this code with Online C++ Compiler
Run Code

Output

Marks = 81

 

Also check out this article - Pair in C++

Member Functions in Classes

There are 2 ways in which we can define member functions in classes:

  1. Outside Class
  2. Inside Class

Outside Class

  • In order to define a member function outside the class, we have to use the scope ‘::’ resolution operator along with the class name followed by the function name.
     

Syntax

Return_type ClassName::Function_Name()

Inside Class

  • All the member functions which are defined inside the class are by default inline. We can make any non-class function inline by using the keyword inline. These are the functions that are copied everywhere during compilation so that the overhead of function calling is reduced.

Constructors in C++

A constructor in C++ is a special member function of a class that initializes objects of the class. It is called automatically when an object is created. Constructors have the same name as the class and do not have a return type.

Syntax:

class ClassName {
public:
    ClassName() {
        // Constructor code here
    }
};

Implementation

  • C++

C++

#include <iostream>
using namespace std;

class Student {
public:
string name;
int roll_no;

// Constructor
Student(string n, int r) {
name = n;
roll_no = r;
cout << "Constructor called for " << name << endl;
}

void display() {
cout << "Name: " << name << ", Roll No: " << roll_no << endl;
}
};

int main() {
// Creating objects
Student student1("Virat", 1);
Student student2("Rohit", 2);

// Displaying student details
student1.display();
student2.display();

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Constructor called for Virat
Constructor called for Rohit
Name: Alice, Roll No: 1
Name: Bob, Roll No: 2

Destructors in C++

A destructor in C++ is a special member function of a class that is executed whenever an object of the class goes out of scope or is explicitly deleted. It has the same name as the class but is preceded by a tilde (~) and does not take any parameters nor does it return a value.

Syntax:

class ClassName {
public:
    ~ClassName() {
        // Destructor code here
    }
};

Implementation

  • C++

C++

#include <iostream>
using namespace std;

class Student {
public:
string name;
int roll_no;

// Constructor
Student(string n, int r) {
name = n;
roll_no = r;
cout << "Constructor called for " << name << endl;
}

// Destructor
~Student() {
cout << "Destructor called for " << name << endl;
}

void display() {
cout << "Name: " << name << ", Roll No: " << roll_no << endl;
}
};

int main() {
// Creating objects
Student student1("Virat", 1);
Student student2("Rohit", 2);

// Displaying student details
student1.display();
student2.display();

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

Constructor called for Virat
Constructor called for Rohit
Name: Alice, Roll No: 1
Name: Bob, Roll No: 2
Destructor called for Virat
Destructor called for Rohit

In this example, the constructor initializes the objects student1 and student2, and the destructor is automatically called when the objects go out of scope at the end of the main function.

Frequently Asked Questions

What are classes and objects in C++?

Classes are blueprints for creating objects, which are instances that hold data and functions defining their behavior.

How many objects in a class?

A class can have any number of objects created from it, limited only by system memory.

Why do we need classes?

Classes provide a way to organize and structure code, promoting reuse, modularity, and encapsulation in object-oriented programming.

What is object class type?

The object class type refers to the specific class from which an object is instantiated, defining its properties and behaviors.

Conclusion

In this blog, we have covered the following topics:

  • Firstly, we discussed what classes and objects are and what their use is.
  • Then we discussed how we can define a class and declare an object.
  • Finally, we discussed the types of access specifiers and different ways to declare member functions.

Classes help us implement the concepts of object-oriented programming in order to study more about object-oriented programming in detail refer to this. Also, to understand more about programming, see the difference between procedural and object-oriented programming in detail.

Recommended Readings:

Live masterclass