Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a class?
3.
What is an Object?
4.
Creating a Class and Declaring Objects
5.
Access Specifier
5.1.
Public
5.2.
Private
5.3.
Protected
6.
Member Functions in Classes
6.1.
Outside Class Definition
6.2.
Inside Class Definition
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

Classes and Objects

gp-icon
Basics of C++
Free guided path
9 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

C++ is an object-oriented language. Everything in C++ is associated with classes and objects, classes are the building blocks of C++ language. It is a user-defined data type, which acts as a blueprint from which objects are created. Classes hold their own data members and member functions, which are accessed using an instance of that class. 

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.

Also see, Literals in C.Fibonacci Series in C++

What is a class?

A class is a user-defined data type, which acts as a blueprint from which objects are created. A class has data members, which are data variables, and member functions which are functions used to manipulate these variables. Data members and member functions together define the behaviour and the properties of the objects of a class.

In the above example of class Student, the data members will be the name, roll no, age, marks, and member functions can be update marks, get age, etc.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is an Object?

An object is any real-world entity, for example, a chair, pencil, rubber, etc. An object is defined as an entity that has a state and behaviour. It is an instance of the Class. When a class is defined, initially, no memory is allocated to it, but when an object is created of that class, memory is allocated for it. 

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.

Recommended Topic: Characteristics of OOPS

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

 

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

#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;
}

 

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

#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;
}


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

#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();

}

 

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:

Outside Class Definition

  • 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 Definition

  • 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.

Must Read: Features of Object Oriented Programming

Know What is Object in OOPs here in detail.

Frequently Asked Questions

Ques: Why do we need classes?

Ans: Classes are used to specify the form of an object, and it combines the data representation and methods which are used for manipulating that data into one package.

Ques: What is the difference between private and protected access specifiers?

Ans: The private access specifier specifies that the members can only be accessed in its own class, whereas the protected access specifier specifies that the members can only be accessed within its own package.

Ques: What is the difference between inline and outline member functions?

Ans: There is no difference between inline and outline member functions in terms of functionality the only difference is inline member functions are defined inside the class, whereas outline member functions are defined outside the class.

Key Takeaways

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:

Previous article
Features of Object Oriented Programming
Next article
Difference between Structure and Class in C++
Guided path
Free
gridgp-icon
Basics of C++
9 chapters
104+ Problems
gp-badge
Earn badges and level up
Live masterclass