In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.
What is a Class in C++?
A class is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is the class, and wheels, speed limits, and mileage are their properties.
- A Class is a user-defined data type that has data members and member functions.
- Data members are the data variables and member functions are the functions used to manipulate these variables together, these data members and member functions define the properties and behaviour of the objects in a Class.
- In the above example of class Car, the data member will be speed limit, mileage, etc, and member functions can be applying brakes, increasing speed, etc.
But we cannot use the class as it is. We first have to create an object of the class to use its features. An Object is an instance of a Class.
Note: When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
Defining Class in C++
A class is defined in C++ using the keyword class followed by the name of the class. The following is the syntax:
class ClassName {
access_specifier:
// Body of the class
};
Here, the access specifier defines the level of access to the class’s data members.
Example
class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};

If you want to dive deep into STL and understand its full potential, our Complete C++ Course offers a complete guide to mastering containers, iterators, and algorithms provided by STL.
What is an Object in C++?
When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax to Create an Object
We can create an object of the given class in the same way we declare the variables of any other inbuilt data type.
ClassName ObjectName;
Example
MyClass obj;
In the above statement, the object of MyClass with name obj is created.
Accessing Data Members and Member Functions
The data members and member functions of the class can be accessed using the dot(‘.’) operator with the object. For example, if the name of the object is obj and you want to access the member function with the name printName() then you will have to write:
obj.printName()
Example of Class and Object in C++
The below program shows how to define a simple class and how to create an object of it.
C++
// C++ program to illustrate how create a simple class and
// object
#include <iostream>
#include <string>
using namespace std;
// Define a class named 'Person'
class Person {
public:
// Data members
string name;
int age;
// Member function to introduce the person
void introduce()
{
cout << "Hi, my name is " << name << " and I am "
<< age << " years old." << endl;
}
};
int main()
{
// Create an object of the Person class
Person person1;
// accessing data members
person1.name = "Alice";
person1.age = 30;
// Call the introduce member method
person1.introduce();
return 0;
}
OutputHi, my name is Alice and I am 30 years old.
Access Modifiers
In C++ classes, we can control the access to the members of the class using Access Specifiers. Also known as access modifier, they are the keywords that are specified in the class and all the members of the class under that access specifier will have particular access level.
In C++, there are 3 access specifiers that are as follows:
- Public: Members declared as public can be accessed from outside the class.
- Private: Members declared as private can only be accessed within the class itself.
- Protected: Members declared as protected can be accessed within the class and by derived classes.
If we do not specify the access specifier, the private specifier is applied to every member by default.
Example of Access Specifiers
C++
// C++ program to demonstrate accessing of data members
#include <bits/stdc++.h>
using namespace std;
class Geeks {
private:
string geekname;
// Access specifier
public:
// Member Functions()
void setName(string name) { geekname = name; }
void printname() { cout << "Geekname is:" << geekname; }
};
int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
// cannot do it like: obj1.geekname = "Abhi";
obj1.setName("Abhi");
// accessing member function
obj1.printname();
return 0;
}
In the above example, we cannot access the data member geekname outside the class. If we try to access it in the main function using dot operator, obj1.geekname, then program will throw an error.
Member Function in C++ Classes
There are 2 ways to define a member function:
- Inside class definition
- Outside class definition
Till now, we have defined the member function inside the class, but we can also define the member function outside the class. To define a member function outside the class definition,
- We have to first declare the function prototype in the class definition.
- Then we have to use the scope resolution:: operator along with the class name and function name.
Example
C++
// C++ program to demonstrate member function
// definition outside class
#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
string geekname;
int id;
// printname is not defined inside class definition
void printname();
// printid is defined inside class definition
void printid() { cout << "Geek id is: " << id; }
};
// Definition of printname using scope resolution operator
// ::
void Geeks::printname()
{
cout << "Geekname is: " << geekname;
}
int main()
{
Geeks obj1;
obj1.geekname = "xyz";
obj1.id = 15;
// call printname()
obj1.printname();
cout << endl;
// call printid()
obj1.printid();
return 0;
}
OutputGeekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition are by default inline, but you can also make any non-class function inline by using the keyword inline with them. Inline functions are actual functions, which are copied everywhere during compilation, like pre-processor macro, so the overhead of function calls is reduced.
Note: Declaring a friend function is a way to give private access to a non-member function.
Constructors
Constructors are special class members which are called by the compiler every time an object of that class is instantiated. Constructors have the same name as the class and may be defined inside or outside the class definition.
There are 4 types of constructors in C++ classes:
- Default Constructors: The constructor that takes no argument is called default constructor.
- Parameterized Constructors: This type of constructor takes the arguments to initialize the data members.
- Copy Constructors: Copy constructor creates the object from an already existing object by copying it.
- Move Constructor: The move constructor also creates the object from an already existing object but by moving it.
Example of Constructor
C++
// C++ program to demonstrate constructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id;
//Default Constructor
Geeks()
{
cout << "Default Constructor called" << endl;
id=-1;
}
//Parameterized Constructor
Geeks(int x)
{
cout <<"Parameterized Constructor called "<< endl;
id=x;
}
};
int main() {
// obj1 will call Default Constructor
Geeks obj1;
cout <<"Geek id is: "<<obj1.id << endl;
// obj2 will call Parameterized Constructor
Geeks obj2(21);
cout <<"Geek id is: " <<obj2.id << endl;
return 0;
}
OutputDefault Constructor called
Geek id is: -1
Parameterized Constructor called
Geek id is: 21
Note: If the programmer does not define the constructor, the compiler automatically creates the default, copy and move constructor.
Destructors
Destructor is another special member function that is called by the compiler when the scope of the object ends. It deallocates all the memory previously used by the object of the class so that there will be no memory leaks. The destructor also have the same name as the class but with tilde(~) as prefix.
Example of Destructor
C++
// C++ program to explain destructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id;
//Definition for Destructor
~Geeks()
{
cout << "Destructor called for id: " << id <<endl;
}
};
int main()
{
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
Geeks obj2;
obj2.id=i;
i++;
} // Scope for obj2 ends here
return 0;
} // Scope for obj1 ends here
OutputDestructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7
Interesting Fact (Rare Known Concept)
Why do we give semicolons at the end of class?
Many people might say that it’s a basic syntax and we should give a semicolon at the end of the class as its rule defines in cpp. But the main reason why semi-colons are there at the end of the class is compiler checks if the user is trying to create an instance of the class at the end of it.
Yes just like structure and union, we can also create the instance of a class at the end just before the semicolon. As a result, once execution reaches at that line, it creates a class and allocates memory to your instance.
C++
#include <iostream>
using namespace std;
class Demo{
int a, b;
public:
Demo() // default constructor
{
cout << "Default Constructor" << endl;
}
Demo(int a, int b):a(a),b(b) //parameterised constructor
{
cout << "parameterized constructor -values" << a << " "<< b << endl;
}
}instance;
int main() {
return 0;
}
OutputDefault Constructor
We can see that we have created a class instance of Demo with the name “instance”, as a result, the output we can see is Default Constructor is called.
Similarly, we can also call the parameterized constructor just by passing values here
C++
#include <iostream>
using namespace std;
class Demo{
public:
int a, b;
Demo()
{
cout << "Default Constructor" << endl;
}
Demo(int a, int b):a(a),b(b)
{
cout << "parameterized Constructor values-" << a << " "<< b << endl;
}
}instance(100,200);
int main() {
return 0;
}
Outputparameterized Constructor values-100 200
So by creating an instance just before the semicolon, we can create the Instance of class.
Related Articles:
Similar Reads
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc. This C++ tutorial is designed to provide a guide for s
6 min read
C++ Overview
Introduction to C++ Programming Language
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language. C++ is a high-level, general-purpose programming language designed for system and application programming. It was dev
7 min read
Features of C++
C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including: Object-Oriented ProgrammingMachine IndependentSimpleHigh-Level LanguagePopu
6 min read
History of C++
The C++ language is an object-oriented programming language & is a combination of both low-level & high-level language - a Middle-Level Language. The programming language was created, designed & developed by a Danish Computer Scientist - Bjarne Stroustrup at Bell Telephone Laboratories (
7 min read
Interesting Facts about C++
C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of
2 min read
Setting up C++ Development Environment
C++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Difference between C and C++
C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
C++ Basics
Writing First C++ Program - Hello World Example
The "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that is used to demonstrate how the coding process works. All you have to do is display the message "Hello World" on the
3 min read
C++ Basic Syntax
Syntax refers to the rules and regulations for writing statements in a programming language. They can also be viewed as the grammatical rules defining the structure of a programming language. The C++ language also has its syntax for the functionalities it provides. Different statements have differen
4 min read
C++ Comments
Comments in C++ are meant to explain the code as well as to make it more readable. Their purpose is to provide information about code lines. When testing alternative code, they can also be used to prevent execution of some part of the code. Programmers commonly use comments to document their work. L
3 min read
Tokens in C
In C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
C++ Keywords
Keywords are the reserved words that have special meanings in the C++ language. They are the words that the language uses for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name or function name or any other identifiers. Let's take a lo
2 min read
Difference between Keyword and Identifier in C
In C, keywords and identifiers are basically the fundamental parts of the language used. Identifiers are the names that can be given to a variable, function or other entity while keywords are the reserved words that have predefined meaning in the language. The below table illustrates the primary dif
3 min read
C++ Variables and Constants
C++ Variables
In C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution. In this article, we will learn about the variables in C++ and how to use them in our programs. Let's take a look at
4 min read
Constants in C
In C programming, constants are read-only values that cannot be modified during the execution of a program. These constants can be of various types, such as integer, floating-point, string, or character constants. They are initialized with the declaration and remain same till the end of the program.
3 min read
Scope of Variables in C++
In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using names
7 min read
Storage Classes in C++ with Examples
C++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specif
7 min read
Static Keyword in C++
The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses. In C++, a static keyword can be used in the following context: Table of Content Static Variables in a FunctionStatic Member Var
5 min read
C++ Data Types and Literals
C++ Data Types
Data types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory. C++ supports a wide variety of data ty
6 min read
Literals in C
In C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, âconst int =
4 min read
Derived Data Types in C++
The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality. In C++, there are four different derived data types: Table of Co
4 min read
User Defined Data Types in C++
User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types: Table of Content ClassStruc
4 min read
Data Type Ranges and Their Macros in C++
Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can
4 min read
C++ Type Modifiers
In C++, type modifiers are the keywords used to change or give extra meaning to already existing data types. It is added to primitive data types as a prefix to modify their size or range of data they can store. C++ have 4 type modifiers which are as follows: Table of Content signed Modifierunsigned
4 min read
Type Conversion in C++
Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { // Two variables of
4 min read
Casting Operators in C++
The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer). Let's take a look at an example: [G
5 min read
C++ Operators
Operators in C++
In C++, an operator is a symbol that operates on a value to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a;
9 min read
C++ Arithmetic Operators
Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands (generally numeric values). An operand can be a variable or a value. For example, â+â is used for addition, '-' is used for subtraction, '*' is used for multiplication, etc. Let's take a look at an
4 min read
Unary Operators in C
In C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
6 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if bot
7 min read
Assignment Operators in C
In C, assignment operators are used to assign values to variables. The left operand is the variable and the right operand is the value being assigned. The value on the right must match the data type of the variable otherwise, the compiler will raise an error. Let's take a look at an example: [GFGTAB
5 min read
C++ sizeof Operator
The sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespac
3 min read
Scope Resolution Operator in C++
In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example: [GFGTABS] C++ #include <iostream> int main() { // Accessing cout from std namespace usin
3 min read
C++ Control Statements
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a s
11 min read
C++ if Statement
The C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example: [GFGTABS] C++ #include <iostream> using namespace std; int
3 min read
C++ if else Statement
The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
4 min read
C++ if else if Ladder
In C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
3 min read
Switch Statement in C++
In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is an alternative to the long if-else-if ladder which provides an easy way to execute different parts of code based on the value of the e
6 min read
Jump statements in C++
Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function. In C++, there is four jump statement: Table of Content continue Statementbreak Statementreturn Statementgot
4 min read
C++ Loops
In C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown. [GFGTABS] C++ #include <iostream> using namesp
7 min read
for Loop in C++
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand. Let's take a look at an example: [GFGTABS] C++ #include <bit
6 min read
Range-Based for Loop in C++
In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops. Let's take
3 min read
C++ While Loop
In C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while Loop
In C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
C++ Functions
Functions in C++
A function is a set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.In s
15+ min read
return Statement in C++
In C++, the return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was calle
4 min read
Parameter Passing Techniques in C
In C, there are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case, A is called the "caller function" and B is called the "called function or callee function". Also, the argum
5 min read
Difference Between Call by Value and Call by Reference in C
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters. The following table lists the differences between the call-by-value and call-by-reference methods of parameter passing. Call By Va
4 min read
Default Arguments in C++
A default argument is a value provided for a parameter in a function declaration that is automatically assigned by the compiler if no value is provided for those parameters in function call. If the value is passed for it, the default value is overwritten by the passed value. Example: [GFGTABS] C++ /
6 min read
Inline Functions in C++
In C++, a function can be specified as inline to reduce the function call overhead. The whole code of the inline function is inserted or substituted at the point of its call during the compilation instead of using normal function call mechanism. Example: [GFGTABS] C++ #include <iostream> using
5 min read
Lambda expression in C++
C++ 11 introduced lambda expressions to allow inline functions which can be used for short snippets of code that are not going to be reused and therefore do not require a name. In their simplest form a lambda expression can be defined as follows: [ capture clause ] (parameters) -> return-type { d
5 min read
C++ Pointers and References
Pointers and References in C++
In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
C++ Pointers
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers. The address of the variable you're workin
9 min read
Dangling, Void , Null and Wild Pointers in C
In C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Applications of Pointers in C
Pointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers Appl
4 min read
Understanding nullptr in C++
Consider the following C++ program that shows problem with NULL (need of nullptr) [GFGTABS] CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Over
3 min read
References in C++
In C++, a reference works as an alias for an existing variable, providing an alternative name for it and allowing you to work with the original data directly. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x;
6 min read
Can References Refer to Invalid Location in C++?
Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the
2 min read
Pointers vs References in C++
Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing
5 min read
When do we pass arguments by pointer?
In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following ca
5 min read