Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 137

Open In App

GEEKSFORGEEKS
C++ Classes and Objects
Class in C++ is the building block that leads to Object-Oriented programming. It 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, 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
behavior 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.
An Object is an instance of a Class. 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 and Declaring Objects


A class is defined in C++ using the keyword class followed by the name of the class. The body of
the class is defined inside the curly brackets and terminated by a semicolon at the end.

C++ Class and Object

Declaring Objects
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
ClassName ObjectName;
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().

Accessing Data Members


The public data members are also accessed in the same way given however the private data
members are not allowed to be accessed directly by the object. Accessing a data member depends
solely on the access control of that data member. This access control is given by Access
modifiers in C++. There are three access modifiers: public, private, and protected.

// C++ program to demonstrate accessing of data members


#include <bits/stdc++.h>

Using namespace std;

Class Geeks {

// Access specifier

Public:

// Data Members

String geekname;
// Member Functions()

Void printname() { cout << “Geekname is:” << geekname; }


};

Int main()
{

// Declare an object of class geeks

Geeks obj1;

// accessing data member

Obj1.geekname = “Abhi”;

// accessing member function

Obj1.printname();

Return 0;
}
Output
Geekname is:Abhi
Member Functions in Classes
There are 2 ways to define a member function:
Inside class definition
Outside class definition
To define a member function outside the class definition we have to use the scope resolution::
operator along with the class name and function name.

// C++ program to demonstrate function


// declaration 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;
}
Output
Geekname 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 3 types of constructors:

Default Constructors
Parameterized Constructors
Copy Constructors
// 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;
}
Output
Default Constructor called
Geek id is: -1
Parameterized Constructor called
Geek id is: 21
A Copy Constructor creates a new object, which is an exact copy of the existing object. The
compiler provides a default Copy Constructor to all the classes.

Syntax:

Class-name (class-name &){}


Destructors
Destructor is another special member function that is called by the compiler when the scope of
the object ends.

// 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


Output
Destructor 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.

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

#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;
}
Output
Parameterized Constructor values-100 200
So by creating an instance just before the semicolon, we can create the Instance of class.

Related Articles:
Multiple Inheritance in C++
Pure Virtual Destructor
C++ Quiz

Article Tags : C++ C++-Class and ObjectCPP-OOPs


Recommended Articles
1. Catching Base and Derived Classes as Exceptions in C++ and Java
2. Enum Classes in C++ and Their Advantage over Enum DataType
3. Pure Virtual Functions and Abstract Classes in C++
4. Passing and Returning Objects in C++
5. Introduction to Complex Objects and Composition
6. Virtual Functions in Derived Classes in C++
7. Local Classes in C++
8. Anonymous classes in C++
9. File Handling through C++ Classes
10. C++ Stream Classes Structure
11. Storage Classes in C++ with Examples
12. Mutual friendship of Classes in C++ with Examples
13. How to add reference of an object in Container Classes
14. Classes vs Structure vs Union in C++
15. Exception Handling using classes in C++
16. Expression Trees Using Classes in C++ with Implementation
17. Self-Referential Classes in C++
18. Calculator using Classes in C++
19. Nested Classes in C++
20. Trivial classes in C++
21. Static Objects in C++
22. Count the number of objects using Static member function
23. How to initialize Array of objects with parameterized constructors in C++
24. Life cycle of Objects in C++ with Example
25. Deletion of array of objects in C++
Read Full Article
A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh – 201305
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Apply for Mentor
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
Tutorials Archive
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
Top 100 DSA Interview Problems
DSA Roadmap by Sandeep Jain
All Cheat Sheets
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
HTML & CSS
HTML
CSS
Web Templates
CSS Frameworks
Bootstrap
Tailwind CSS
SASS
LESS
Web Design
Python
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Python Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
Competitive Programming
Top DS or Algo for CP
Top 50 Tree
Top 50 Graph
Top 50 Array
Top 50 String
Top 50 DP
Top 15 Websites for CP
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
JavaScript
JavaScript Examples
TypeScript
ReactJS
NextJS
AngularJS
NodeJS
Lodash
Web Browser
NCERT Solutions
Class 12
Class 11
Class 10
Class 9
Class 8
Complete Study Material
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Indian Economics
Macroeconomics
Microeconimics
Statistics for Economics
Management & Finance
Management
HR Managament
Income Tax
Finance
Economics
UPSC Study Material
Polity Notes
Geography Notes
History Notes
Science and Technology Notes
Economy Notes
Ethics Notes
Previous Year Papers
SSC/ BANKING
SSC CGL Syllabus
SBI PO Syllabus
SBI Clerk Syllabus
IBPS PO Syllabus
IBPS Clerk Syllabus
SSC CGL Practice Papers
Colleges
Indian Colleges Admission & Campus Experiences
List of Central Universities – In India
Colleges in Delhi University
IIT Colleges
NIT Colleges
IIIT Colleges
Companies
META Owned Companies
Alphabhet Owned Companies
TATA Group Owned Companies
Reliance Owned Companies
Preparation Corner
Company Wise Preparation
Preparation for SDE
Experienced Interviews
Internship Interviews
Competitive Programming
Aptitude Preparation
Puzzles
Exams
JEE Mains
JEE Advanced
GATE CS
NEET
UGC NET
More Tutorials
Software Development
Software Testing
Product Management
SAP
SEO – Search Engine Optimization
Linux
Excel
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

Skip to content
PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Log In

MENU
C++ PROGRAMMING
What is Member Function in C++?
Last Updated on April 17, 2023 by Prepbytes

A member function in C++ is a function that is part of a class. It is used to manipulate the data
members of the class. Member functions are also known as methods. Member functions are
declared inside the class definition and can be defined either inside or outside the class
definition. A function declared as a member of the class is called a member function. Generally,
member functions are declared as public because they have to be called outside of the class.
Member functions are very useful to achieve OOPs concept encapsulation which is used to
access private data members of the class using public member functions. In this article, we will
learn about member function in-depth, ways to define member function, and types of member
function

Member Function
A function is a Member Function if it can be declared as a member of the class (Function
declaration or definition within the class). Member Functions can be declared within the class as
public, private, or protected functions. Member Functions may be used to read, manipulate, or
display all types of data members (private, public, and protected). Member Function is declared
as any other variable in C++.
Example of Member Function in C++
Let’s understand what a member function is in C++ with the help of an example?

C++
# include <iostream>
Using namespace std;
Class Employee{
Int employee_id;
String employee_name;
String employee_tech;
Double employee_salary;
Public:
String getDetails(int employee_id);
}
</iostream>
In the above example, we can say the getDetails function is a Member Function in C++. Here
only a declaration of the Member function is given. We can provide function definitions also.

How to define Member Functions in C++?


There are mainly two ways to define Member Function in C++.

Definition within the Class


Definition outside the Class
Defining Member Function within the Class
We can give a definition of the function within the class to define Member Function. This
method of defining Member Function is generally used when a definition of function is short.
Member functions in C++ has all the access to data members and other member functions of the
same class.
Let’s understand how to define Member Function in C++ within the class with the help of an
example.

C++
# include <iostream>
Using namespace std
Class Employee{
Int employee_id;
String employee_name;
String employee_tech;
Double employee_salary;
Public:
Void setId(int id){
// definition of the function
Employee_id = id;
}
Void setName(string name){
Employee_name = name;
}
Void setTech(string tech){
Employee_tech = tech;
}
Void setSalary(double salary){
Employee_salary = salary;
}
Int getId(){
Return employee_id;
}
String getName(){
Return empoyee_name;
}
String getTech(){
Return employee_tech;
}
Double getSalary(){
Return employee_salary;
}
}
In the above example we have defined the function setId (definition = employee_id=id ). We
have defined other functions like setName, setTech, setSalary, getName, getId, etc. We can create
an object of class Employee and we can use above defined functions to set values of the private
variable (ex:- id, name, tech, salary). We can also use the defined function to get the values of the
private variables. The problem with this method is when we write long definitions it’s become
more complex to read the code.

Defining Member Function outside the Class


In this method, we can declare a function within the class and we define the function outside the
class to achieve the Member Function in C++. While using this method we need to ensure that
the function is declared within the class. The problem with this method is when we have more
than one class having the same function name so it will be confusing which function’s definition
it is.

Below is a small example given to understand the problem?

Class Circle{
Int size;
Public:
Void printSize(int s);
}

Class Square{
Int size;
Public:
Void printSize(int s);
}
We can see that there is the same function [ printSize( int s ) ] in both classes ( Circle, Square ).
To avoid this problem we can use the scope resolution operator (:. The syntax of using the
scope resolution operator to achieve Member Function in C++ is given below.

Return_type class_name :: member_function_name (arguments){


// definition of the function
}
Let’s see how we can define the member function of both classes ( Circle, Square ) using the
scope resolution operator and the above syntax.

Void Circle :: printSize(int s){


Cout<< s <<endl;
}

Void Square :: printSize(int s){


Count<< s <<endl;
}
Now lets understand this method of defining Member Function in C++ using an example. We
will use the same example as method 1 to understand the difference between the two methods.

C++
# include <iostream>
Using namespace std;
Class Employee{
Int employee_id;
String employee_name;
String employee_tech;
Double employee_salary;
Public:
// only declaration of the functions
Void setId(int id);
Void setName(string name);
Void setTech(string tech);
Void setSalary(double salary);
Int getId();
String getName();
String getTech();
Double getSalary();
}
// definition of the functions outside the class
Void Employee :: setId(int id){
Employee_id=id;
}
Void Employee :: setName(int name){
Employee_name=name;
}
Void Employee :: setTech(int tech){
Employee_tech=tech;
}
Void Employee :: setSalary(int salary){
Employee_salary=salary;
}
Int Employee :: getId(){
Return employee_id;
}
String Employee :: getName(){
Return employee_name;
}
String Employee :: getTech(){
Return employee_tech;
}
Double Employee :: getSalary(){
Return employee_salary;
}
}
In the above example, we can see that we have only declared the member functions [ex:- getId(),
setId(), etc. ] in the class itself and we define the function outside the class Employee using the
scope resolution operator. This method of defining the Member Function in C++ is generally
used when the definition of the function is large. This method is very efficient and readable.

Types of Member Function in C++


There are five types of Member Function in C++.
Simple Function
Const Function
Static Function
Inline Function
Friend Function
Simple Function
Simple Functions are declared without using any specific keyword ( ex:- static, const ). Simple
Functions do not have any specific behavior.

C++
#include <iostream>
Using namespace std;
Class Shape{
Public:
// Simple Member Function
Int square(int length){
Return length*length;
}
}
</iostream>
Const Function
Constant Functions are functions that are not able to modify data members of the class. We can
declare Const Function using the const keyword at the end of the arguments parenthesis. The
syntax of the Const Function is given below.

Syntax :-
Return_type function_name ( arguments ) **const ;**
C++
#include <iostream>
Using namespace std;
Class Shape{
Int length;
Public:
Shape(int len=0){
Length=len; // data member can be assigned only once
}
// Const Member Function
Int square(int len) const{
// length=10; if we uncomment this line code will throw an error because we can’t
modify the data member
Return length*length;
}
};
Static Function
Static Functions are created using static keyword before the return type of function declaration.
Static Functions can only call static members and static functions inside the static function
definition because Static members functions do not have implicit this argument. We can direct
call Static Functions without creating an object of the class. Using the scope resolution operator
(: we can call the static function directly.

C++
#include <iostream>
Using namespace std;
Class Shape{
Public:
// Static Function
Static int square(int length){
Return length*length;
}
};
Int main(){
// call Static Function without creating an object of class
Std::cout << Shape::square(10) << std::endl;
Return 0;
}
Inline Function
Inline Functions are created using the inline keyword before the return type of the function
declaration. Inline Functions are used to reduce overhead function calling. Inline Function may
increase efficiency of the code if it has a small definition.

C++
#include <iostream>
Using namespace std;
Inline int square(int length){
Return length*length;
}
Int main(){
Std::cout << square(10) << std::endl;
Return 0;
}
Friend Function
Friends Functions are functions that have their definition outside (non-member function) of the
class but they can still access private and protected members of the class. To access private and
protected members outside the class definition of the Friend Function should be inside the class.
Friend Functions are declared inside the class using a friend keyword before the return type of
the function.

C++
#include <iostream>
Using namespace std;
Class Shape{
Int length; // private member of the class
Public:
// friend function declaration
Friend int square(int len);
};
// definition of friend function
Int square(int len){
Shape s;
s.length=len; // access private variable
return s.length*s.length;
}
Int main(){
Std::cout << square(10) << std::endl;
Return 0;
}
FAQs of Member Function in C++
1. What is a non member function in C++?
Non-member functions are the opposite of member functions, non-member functions are
declared outside the class.
Example:-

#include <iostream>
Using namespace std;

Class Shape{
Public:
// Member Function
Int square(int len);
};

// Non-member Function
Int rectangle(int length,int breadth){
Return length*breadth;
}
2. What is the member variable C++?
Member variables are declared within the class only and member variables are accessible by the
function of that same class (Member Function).

Example:-

Class Shape{
Int length; // member variable
Public:
// Member Function
Int square(int len);
};
3. What is the difference between function and member function?
A normal function is always declared outside the class and a member function is always declared
within the class (it can be defined outside the class).

Example:-

#include <iostream>
Using namespace std;

Class Shape{
Int length;
Public:
// Member Function
Int square(int len);
};

// Normal Function
Int rectangle(int length,int breadth){
Return length*breadth;
}
4. What are the characteristics of member functions?
Member Functions with the same name can be used in multiple classes.
The private member or private function of the class can be accessed by the Member Function in
C++.
We can pass the default argument in Member Function as well [ex: int square(int length=10) here
we pass default length as 10 ].
A Member Function can access any other member of their class without using the dot (.)
operator.
5. Can we overload member functions in C++?
Yes, we can overload member function in C++. Below is the given example of member function
overload.

Example:-

#include <iostream>
Using namespace std;

Class Shape{
Int length;
Public:
// Member Functions with different return type or arguments (overload)
Int square(int length){
Return length*length;
}

Float square(float length){


Return length*length;
}
};

Int main(){
Shape s;
Float length1=10.1;
Int length2=10;
Std::cout << s.square(length1) << std::endl;
Std::cout << s.square(length2) << std::endl;
Return 0;
}
Post navigation
Previous
Previous post:
Commonly Asked DBMS Interview Questions And Answers
Next
Next post:
Difference between C and Java Language
Leave a Reply
Your email address will not be published. Required fields are marked *

Comment *

Name *
Email *
Website
Save my name, email, and website in this browser for the next time I comment.

Search for:
Search …
Pages
ALGORITHMS
ARRAY
BACKTRACKING
C PROGRAMMING LANGUAGE
C++ PROGRAMMING LANGUAGE
CAPGEMINI
CIRCULAR LINKED LIST
COMPANY PLACEMENT PROCEDURE
COMPETITIVE CODING
COMPUTATIONAL GEOMETRY
CSE SUBJECTS
DATA STRUCTURE
DOUBLY LINKED LIST
DYNAMIC PROGRAMMING
GAME THEORY
GRAPHS
GREEDY ALGORITHM
HASHING
HEAP
INTERVIEW PREPARATION
INTERVIEW TIPS
JAVA PROGRAMMING LANGUAGE
JAVASCRIPT PROGRAMMING LANGUAGE
Languages
LINKED LIST
LINKED LIST USING C
MATHEMATICS
OPERATING SYSTEM
POINTERS
PYTHON PROGRAMMING LANGUAGE
QUEUE
RECURSION
SEARCHING
SEGMENT TREE
SORTING
STACK
STRING
TREES
Recent Articles
1
JANUARY 25, 2024
Join Operation Vs Nested Query
2
JANUARY 25, 2024
Dimensional Data Modeling
3
JANUARY 25, 2024
Star Schema in Data Warehouse modeling
4
JANUARY 25, 2024
Selfish Round Robin Scheduling
5
JANUARY 25, 2024
Convoy Effect in Operating Systems
6
JANUARY 24, 2024
Leaky Bucket Algorithm
CLOSE
Search for:
Search …
MENU
Language
Data Structure
Algorithm
CSE Subjects
Company Placement
Interview
Competitive
Others
Related Post
Restoring Division Algo for unsigned integer
AUGUST 10, 2023
Adding Functions To Library
JULY 5, 2023
Vector Pair In C++
JUNE 16, 2023
Infix to Postfix Conversion Using Stack in C++
MAY 30, 2023
Array Rotation in C++
MAY 12, 2023
Reverse Elements of an Array in C++
MAY 11, 2023
FOLLOW US
CONTACT US
+91-7969002111
contact@prepbytes.com
QUICK LINKS
Interview NotesMock TestsPlacement ProgrammeCoding CoursesMock InterviewAbout UsBlog
Go To TopJavatpoint Logo

Home
C++
C
C#
Java
PHP
HTML
CSS
JavaScript
jQuery
XML
JSON
Ajax
Node.js
SQL
Projects
Interview Q

Static Member Function in C++


The static is a keyword in the C and C++ programming language. We use the static keyword to
define the static data member or static member function inside and outside of the class. Let’s
understand the static data member and static member function using the programs.

Static Member Function in C++


Static data member
ADVERTISEMENT
When we define the data member of a class using the static keyword, the data members are
called the static data member. A static data member is similar to the static member function
because the static data can only be accessed using the static data member or static member
function. And, all the objects of the class share the same copy of the static member to access the
static data.

Syntax

ADVERTISEMENT
Static data_type data_member;
Here, the static is a keyword of the predefined library.

The data_type is the variable type in C++, such as int, float, string, etc.

The data_member is the name of the static data.

ADVERTISEMENT
Example 1: Let’s create a simple program to access the static data members in the C++
programming language.

#include <iostream>
#include <string.h>
Using namespace std;
// create class of the Car
Class Car
{
Private:
Int car_id;
Char car_name[20];
Int marks;

Public:
// declare a static data member
Static int static_member;

Car()
{
Static_member++;
}

Void inp()
{
Cout << “ \n\n Enter the Id of the Car: “ << endl;
Cin >> car_id; // input the id
Cout << “ Enter the name of the Car: “ << endl;
Cin >> car_name;
Cout << “ Number of the Marks (1 – 10): “ << endl;
Cin >> marks;
}
// display the entered details
Void disp ()
{
Cout << “ \n Id of the Car: “ << car_id;
Cout << “\n Name of the Car: “ << car_name;
Cout << “ \n Marks: “ << marks;

}
};

// initialized the static data member to 0


Int Car::static_member = 0;

Int main ()
{
// create object for the class Car
Car c1;
// call inp() function to insert values
C1. Inp ();
C1. Disp();

//create another object


Car c2;
// call inp() function to insert values
C2. Inp ();
C2. Disp();
Cout << “ \n No. Of objects created in the class: “ << Car :: static_member <<endl;
Return 0;
}
Output

ADVERTISEMENT
Enter the Id of the Car:
101
Enter the name of the Car:
Ferrari
Number of the Marks (1 – 10):
10

Id of the Car: 101


Name of the Car: Ferrari
Marks: 10

Enter the Id of the Car:


205
Enter the name of the Car:
Mercedes
Number of the Marks (1 – 10):
9

Id of the Car: 205


Name of the Car: Mercedes
Marks: 9
No. Of objects created in the class: 2
Static Member Functions
ADVERTISEMENT
The static member functions are special functions used to access the static data members or other
static member functions. A member function is defined using the static keyword. A static member
function shares the single copy of the member function to any number of the class’ objects. We
can access the static member function using the class name or class’ objects. If the static member
function accesses any non-static data member or non-static member function, it throws an error.

Syntax

ADVERTISEMENT
Class_name::function_name (parameter);
ADVERTISEMENT
Here, the class_name is the name of the class.

Function_name: The function name is the name of the static member function.

Parameter: It defines the name of the pass arguments to the static member function.

Example 2: Let’s create another program to access the static member function using the class
name in the C++ programming language.

#include <iostream>
Using namespace std;
Class Note
{
// declare a static data member
Static int num;

Public:
// create static member function
Static int func ()
{
Return num;
}
};
// initialize the static data member using the class name and the scope resolution operator
Int Note :: num = 5;

Int main ()
{
// access static member function using the class name and the scope resolution
Cout << “ The value of the num is: “ << Note:: func () << endl;
Return 0;
}
ADVERTISEMENT
Output

The value of the num is: 5


Example 3: Let’s create another program to access the static member function using the class’
object in the C++ programming language.

#include <iostream>
Using namespace std;
Class Note
{
// declare a static data member
Static int num;

Public:
// create static member function
Static int func ()
{
Cout << “ The value of the num is: “ << num << endl;
}
};
// initialize the static data member using the class name and the scope resolution operator
Int Note :: num = 15;

Int main ()
{
// create an object of the class Note
Note n;
// access static member function using the object
n.func();

return 0;
}
Output
The value of the num is: 15
Example 4: Let’s consider an example to access the static member function using the object and
class in the C++ programming language.

#include <iostream>
Using namespace std;
Class Member
{

Private:
// declaration of the static data members
Static int A;
Static int B;
Static int C;

// declare public access specifier


Public:
// define the static member function
Static void disp ()
{
Cout << “ The value of the A is: “ << A << endl;
Cout << “ The value of the B is: “ << B << endl;
Cout << “ The value of the C is: “ << C << endl;
}
};
// initialization of the static data members
Int Member :: A = 20;
Int Member :: B = 30;
Int Member :: C = 40;

Int main ()
{
// create object of the class Member
Member mb;
// access the static member function using the class object name
Cout << “ Print the static member through object name: “ << endl;
Mb. Disp();
// access the static member function using the class name
Cout << “ Print the static member through the class name: “ << endl;
Member::disp();
Return 0;
}
Output

Print the static member through object name:


The value of the A is: 20
The value of the B is: 30
The value of the C is: 40
Print the static member through the class name:
The value of the A is: 20
The value of the B is: 30
The value of the C is: 40
← PrevNext →

Youtube For Videos Join Our Youtube Channel: Join Now


Feedback
Send your Feedback to feedback@javatpoint.com
Help Others, Please Share
Facebook twitter pinterest

Learn Latest Tutorials


Splunk tutorial
Splunk

SPSS tutorial
SPSS

Swagger tutorial
Swagger

T-SQL tutorial
Transact-SQL

Tumblr tutorial
Tumblr

React tutorial
ReactJS
Regex tutorial
Regex

Reinforcement learning tutorial


Reinforcement Learning

R Programming tutorial
R Programming

RxJS tutorial
RxJS

React Native tutorial


React Native

Python Design Patterns


Python Design Patterns

Python Pillow tutorial


Python Pillow

Python Turtle tutorial


Python Turtle

Keras tutorial
Keras
Preparation
Aptitude
Aptitude

Logical Reasoning
Reasoning

Verbal Ability
Verbal Ability

Interview Questions
Interview Questions

Company Interview Questions


Company Questions

Trending Technologies
Artificial Intelligence
Artificial Intelligence

AWS Tutorial
AWS

Selenium tutorial
Selenium
Cloud Computing
Cloud Computing

Hadoop tutorial
Hadoop

ReactJS Tutorial
ReactJS

Data Science Tutorial


Data Science

Angular 7 Tutorial
Angular 7

Blockchain Tutorial
Blockchain

Git Tutorial
Git

Machine Learning Tutorial


Machine Learning

DevOps Tutorial
DevOps
B.Tech / MCA
DBMS tutorial
DBMS

Data Structures tutorial


Data Structures

DAA tutorial
DAA

Operating System
Operating System

Computer Network tutorial


Computer Network

Compiler Design tutorial


Compiler Design

Computer Organization and Architecture


Computer Organization

Discrete Mathematics Tutorial


Discrete Mathematics
Ethical Hacking
Ethical Hacking

Computer Graphics Tutorial


Computer Graphics

Software Engineering
Software Engineering

Html tutorial
Web Technology

Cyber Security tutorial


Cyber Security

Automata Tutorial
Automata

C Language tutorial
C Programming

C++ tutorial
C++

Java tutorial
Java
.Net Framework tutorial
.Net

Python tutorial
Python

List of Programs
Programs

Control Systems tutorial


Control System

Data Mining Tutorial


Data Mining

Data Warehouse Tutorial


Data Warehouse

Open In App

GEEKSFORGEEKS
Array of Objects in C++ with Examples
An array in C/C++ or be it in any programming language is a collection of similar data items
stored at contiguous memory locations and elements can be accessed randomly using indices of
an array. They can be used to store the collection of primitive data types such as int, float,
double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data
types such as structures, pointers, etc. Given below is the picture representation of an array.
Example:
Let’s consider an example of taking random integers from the user.

Array allocation
Array

Array of Objects

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:

ClassName ObjectName[number of objects];


The Array of Objects stores objects. An array of a class type is also known as an array of objects.

Example#1:
Storing more than one Employee data. Let’s assume there is an array of objects for storing
employee data emp[50].

Array of objects

Below is the C++ program for storing data of one Employee:

// C++ program to implement


// the above approach
#include<iostream>

Using namespace std;

Class Employee
{

Int id;

Char name[30];

Public:

Void getdata();//Declaration of function

Void putdata();//Declaration of function


};

Void Employee::getdata(){//Defining of function

Cout<<”Enter Id : “;

Cin>>id;

Cout<<”Enter Name : “;
Cin>>name;
}

Void Employee::putdata(){//Defining of function

Cout<<id<<” “;

Cout<<name<<” “;

Cout<<endl;
}

Int main(){

Employee emp; //One member

Emp.getdata();//Accessing the function

Emp.putdata();//Accessing the function

Return 0;

}
Let’s understand the above example –

In the above example, a class named Employee with id and name is being considered.
The two functions are declared-
Getdata(): Taking user input for id and name.
Putdata(): Showing the data on the console screen.
This program can take the data of only one Employee. What if there is a requirement to add data
of more than one Employee. Here comes the answer Array of Objects. An array of objects can be
used if there is a need to store data of more than one employee. Below is the C++ program to
implement the above approach-

// C++ program to implement


// the above approach
#include<iostream>

Using namespace std;

Class Employee
{

Int id;

Char name[30];

Public:

// Declaration of function
Void getdata();

// Declaration of function

Void putdata();
};

// Defining the function outside


// the class

Void Employee::getdata()
{

Cout << “Enter Id : “;

Cin >> id;

Cout << “Enter Name : “;

Cin >> name;


}

// Defining the function outside


// the class
Void Employee::putdata()
{

Cout << id << “ “;

Cout << name << “ “;

Cout << endl;


}

// Driver code

Int main()
{

// This is an array of objects having

// maximum limit of 30 Employees

Employee emp[30];

Int n, i;

Cout << “Enter Number of Employees – “;

Cin >> n;
// Accessing the function

For(i = 0; i < n; i++)

Emp[i].getdata();

Cout << “Employee Data – “ << endl;

// Accessing the function

For(i = 0; i < n; i++)

Emp[i].putdata();
}
Output:

Explanation:
In this example, more than one Employee’s details with an Employee id and name can be stored.
Employee emp[30] – This is an array of objects having a maximum limit of 30 Employees.
Two for loops are being used-
First one to take the input from user by calling emp[i].getdata() function.
Second one to print the data of Employee by calling the function emp[i].putdata() function.
Example#2:

// C++ program to implement


// the above approach
#include<iostream>

Using namespace std;

Class item
{

Char name[30];

Int price;

Public:

Void getitem();

Void printitem();
};
// Function to get item details

Void item::getitem()
{

Cout << “Item Name = “;

Cin >> name;

Cout << “Price = “;

Cin >> price;


}

// Function to print item


// details

Void item ::printitem()


{

Cout << “Name : “ << name <<

“\n”;

Cout << “Price : “ << price <<

“\n”;
}

Const int size = 3;

// Driver code

Int main()
{

Item t[size];

For(int i = 0; i < size; i++)

Cout << “Item : “ <<

(i + 1) << “\n”;

T[i].getitem();

For(int i = 0; i < size; i++)


{

Cout << “Item Details : “ <<

(i + 1) << “\n”;

T[i].printitem();

}
}
Output:

Advantages of Array of Objects:

The array of objects represent storing multiple objects in a single name.


In an array of objects, the data can be accessed randomly by using the index number.
Reduce the time and memory by storing the data in a single variable.

Article Tags : C++ ArraysC++-Class and Object


Recommended Articles
1. Extract unique objects by attribute from array of objects
2. How to initialize Array of objects with parameterized constructors in C++
3. Deletion of array of objects in C++
4. Passing array of objects as parameter in C++
5. How to Parse an Array of Objects in C++ Using RapidJson?
6. Static Objects in C++
7. Count the number of objects using Static member function
8. Passing and Returning Objects in C++
9. Introduction to Complex Objects and Composition
10. Life cycle of Objects in C++ with Example
11. Anonymous Objects in C++
12. Creating a Vector of Class Objects in C++
13. Reference to Dynamic Objects in C++
14. How to make a C++ class whose objects can only be dynamically allocated?
15. How to Restrict Dynamic Allocation of Objects in C++?
16. C++ Classes and Objects
17. Comparing String objects using Relational Operators in C++
18. Read/Write Class Objects from/to File in C++
19. What’s difference between “array” and “&array” for “int array[5]” ?
20. Check whether an array can be fit into another array rearranging the elements in the array
21. array data() in C++ STL with Examples
22. Convert given Binary Array to String in C++ with Examples
23. Array of maps in C++ with Examples
24. Array of unordered maps in C++ with Examples
25. Array of list in C++ with Examples
Read Full Article
A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh – 201305
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Apply for Mentor
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
Tutorials Archive
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
Top 100 DSA Interview Problems
DSA Roadmap by Sandeep Jain
All Cheat Sheets
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
HTML & CSS
HTML
CSS
Web Templates
CSS Frameworks
Bootstrap
Tailwind CSS
SASS
LESS
Web Design
Python
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Python Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
Competitive Programming
Top DS or Algo for CP
Top 50 Tree
Top 50 Graph
Top 50 Array
Top 50 String
Top 50 DP
Top 15 Websites for CP
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
JavaScript
JavaScript Examples
TypeScript
ReactJS
NextJS
AngularJS
NodeJS
Lodash
Web Browser
NCERT Solutions
Class 12
Class 11
Class 10
Class 9
Class 8
Complete Study Material
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Indian Economics
Macroeconomics
Microeconimics
Statistics for Economics
Management & Finance
Management
HR Managament
Income Tax
Finance
Economics
UPSC Study Material
Polity Notes
Geography Notes
History Notes
Science and Technology Notes
Economy Notes
Ethics Notes
Previous Year Papers
SSC/ BANKING
SSC CGL Syllabus
SBI PO Syllabus
SBI Clerk Syllabus
IBPS PO Syllabus
IBPS Clerk Syllabus
SSC CGL Practice Papers
Colleges
Indian Colleges Admission & Campus Experiences
List of Central Universities – In India
Colleges in Delhi University
IIT Colleges
NIT Colleges
IIIT Colleges
Companies
IT Companies
Software Development Companies
Artificial Intelligence(AI) Companies
CyberSecurity Companies
Service Based Companies
Product Based Companies
PSUs for CS Engineers
Preparation Corner
Company Wise Preparation
Preparation for SDE
Experienced Interviews
Internship Interviews
Competitive Programming
Aptitude Preparation
Puzzles
Exams
JEE Mains
JEE Advanced
GATE CS
NEET
UGC NET
More Tutorials
Software Development
Software Testing
Product Management
SAP
SEO – Search Engine Optimization
Linux
Excel
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Open In App

GEEKSFORGEEKS
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared
as a friend. It is sometimes useful to allow a particular class to access private and protected
members of other classes. For example, a LinkedList class may be allowed to access private
members of Node.

We can declare a friend class in C++ by using the friend keyword.

Syntax:

Friend class class_name; // declared in the base class

Friend class

Example:

// C++ Program to demonstrate the


// functioning of a friend class
#include <iostream>

Using namespace std;


Class GFG {

Private:

Int private_variable;

Protected:

Int protected_variable;

Public:

GFG()

Private_variable = 10;

Protected_variable = 99;

// friend class declaration


Friend class F;
};

// Here, class F is declared as a


// friend inside class GFG. Therefore,
// F is a friend of class GFG. Class F
// can access the private members of
// class GFG.

Class F {

Public:

Void display(GFG& t)

Cout << “The value of Private Variable = “

<< t.private_variable << endl;

Cout << “The value of Protected Variable = “

<< t.protected_variable;

}
};

// Driver code

Int main()
{

GFG g;

F fri;

Fri.display(g);

Return 0;
}
Output
The value of Private Variable = 10
The value of Protected Variable = 99
Note: We can declare friend class or function anywhere in the base class body whether its
private, protected or public block. It works all the same.

Friend Function
Like a friend class, a friend function can be granted special access to private and protected
members of a class in C++. They are the non-member functions that can access and manipulate
the private and protected members of the class for they are declared as friends.

A friend function can be:


A global function
A member function of another class

Friend Function in C++ with Example


Friend Function in C++

Syntax:

Friend return_type function_name (arguments); // for a global function


Or
Friend return_type class_name::function_name (arguments); // for a member function of
another class

Friend function syntax


Friend Function Syntax

1. Global Function as Friend Function


We can declare any global function as a friend function. The following example demonstrates
how to declare a global function as a friend function in C++:

Example:

// C++ program to create a global function as a friend


// function of some class
#include <iostream>

Using namespace std;


Class base {

Private:

Int private_variable;

Protected:

Int protected_variable;

Public:

Base()

Private_variable = 10;

Protected_variable = 99;

}
// friend function declaration

Friend void friendFunction(base& obj);


};

// friend function definition

Void friendFunction(base& obj)


{

Cout << “Private Variable: “ << obj.private_variable

<< endl;

Cout << “Protected Variable: “ << obj.protected_variable;


}

// driver code

Int main()
{

Base object1;

friendFunction(object1);
return 0;
}
Output
Private Variable: 10
Protected Variable: 99
In the above example, we have used a global function as a friend function. In the next example,
we will use a member function of another class as a friend function.

2. Member Function of Another Class as Friend Function


We can also declare a member function of another class as a friend function in C++. The
following example demonstrates how to use a member function of another class as a friend
function in C++:

Example:

// C++ program to create a member function of another class


// as a friend function
#include <iostream>

Using namespace std;

Class base; // forward definition needed


// another class in which function is declared

Class anotherClass {
Public:

Void memberFunction(base& obj);


};

// base class for which friend is declared

Class base {

Private:

Int private_variable;

Protected:

Int protected_variable;

Public:

Base()

Private_variable = 10;
Protected_variable = 99;

// friend function declaration

Friend void anotherClass::memberFunction(base&);


};

// friend function definition

Void anotherClass::memberFunction(base& obj)


{

Cout << “Private Variable: “ << obj.private_variable

<< endl;

Cout << “Protected Variable: “ << obj.protected_variable;


}

// driver code

Int main()
{
Base object1;

anotherClass object2;

object2.memberFunction(object1);

return 0;
}
Output
Private Variable: 10
Protected Variable: 99
Note: The order in which we define the friend function of another class is important and should
be taken care of. We always have to define both the classes before the function definition. Thats
why we have used out of class member function definition.

Features of Friend Functions


A friend function is a special function in C++ that in spite of not being a member function of a
class has the privilege to access the private and protected data of a class.
A friend function is a non-member function or ordinary function of a class, which is declared as a
friend using the keyword “friend” inside the class. By declaring a function as a friend, all the
access permissions are given to the function.
The keyword “friend” is placed only in the function declaration of the friend function and not in
the function definition or call.
A friend function is called like an ordinary function. It cannot be called using the object name
and dot operator. However, it may accept the object as an argument whose value it wants to
access.
A friend function can be declared in any section of the class i.e. public or private or protected.
Below are some more examples of friend functions in different scenarios:
A Function Friendly to Multiple Classes
// C++ Program to demonstrate
// how friend functions work as
// a bridge between the classes
#include <iostream>

Using namespace std;

// Forward declaration

Class ABC;

Class XYZ {

Int x;

Public:

Void set_data(int a)

X = a;

}
Friend void max(XYZ, ABC);
};

Class ABC {

Int y;

Public:

Void set_data(int a)

Y = a;

Friend void max(XYZ, ABC);


};

Void max(XYZ t1, ABC t2)


{

If (t1.x > t2.y)

Cout << t1.x;

Else

Cout << t2.y;


}

// Driver code

Int main()
{

ABC _abc;

XYZ _xyz;

_xyz.set_data(20);

_abc.set_data(35);

// calling friend function


Max(_xyz, _abc);

Return 0;
}
Output
35
The friend function provides us with a way to access private data but it also has its demerits.
Following is the list of advantages and disadvantages of friend functions in C++:

Advantages of Friend Functions


A friend function is able to access members without the need of inheriting the class.
The friend function acts as a bridge between two classes by accessing their private data.
It can be used to increase the versatility of overloaded operators.
It can be declared either in the public or private or protected part of the class.
Disadvantages of Friend Functions
Friend functions have access to private members of a class from outside the class which violates
the law of data hiding.
Friend functions cannot do any run-time polymorphism in their members.
Important Points About Friend Functions and Classes
Friends should be used only for limited purposes. Too many functions or external classes are
declared as friends of a class with protected or private data access lessens the value of
encapsulation of separate classes in object-oriented programming.
Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A
automatically.
Friendship is not inherited. (See this for more details)
The concept of friends is not in Java.

Article Tags : C++ cpp-friend


Recommended Articles
1. Can We Access Private Data Members of a Class without using a Member or a Friend
Function in C++?
2. Difference Between Friend Function and Virtual Function in C++
3. Difference between Static and Friend Function in C++
4. C++ Program to swap two members using Friend Function
5. Using Non-Member Friend Functions With Vector in C++ STL
6. Behavior of virtual function in the derived class from the base class and abstract class
7. Difference between Base class and Derived class in C++
8. How to convert a class to another class type in C++?
9. Base Class Pointer Pointing to Derived Class Object in C++
10. C++ interview questions on virtual function and abstract class
11. Calling a non-member function inside a class in C++
12. Difference between Virtual function and Pure virtual function in C++
13. Difference between virtual function and inline function in C++
14. error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in
C++
15. How to call function within function in C or C++
16. Returning a function pointer from a function in C/C++
17. What happens when a virtual function is called inside a non-virtual function in C++
18. Function Overloading vs Function Overriding in C++
19. Difference Between Structure and Class in C++
20. Difference between namespace and class
21. Operator Overloading ‘<<’ and ‘>>’ operator in a linked list class
22. Difference between Shallow and Deep copy of a class
23. Why overriding both the global new operator and the class-specific operator is not
ambiguous?
24. Difference Between Object And Class
25. C++ string class and its applications
Read Full Article
A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh – 201305
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Apply for Mentor
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
Tutorials Archive
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
Top 100 DSA Interview Problems
DSA Roadmap by Sandeep Jain
All Cheat Sheets
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
HTML & CSS
HTML
CSS
Web Templates
CSS Frameworks
Bootstrap
Tailwind CSS
SASS
LESS
Web Design
Python
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Python Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
Competitive Programming
Top DS or Algo for CP
Top 50 Tree
Top 50 Graph
Top 50 Array
Top 50 String
Top 50 DP
Top 15 Websites for CP
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
JavaScript
JavaScript Examples
TypeScript
ReactJS
NextJS
AngularJS
NodeJS
Lodash
Web Browser
NCERT Solutions
Class 12
Class 11
Class 10
Class 9
Class 8
Complete Study Material
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Indian Economics
Macroeconomics
Microeconimics
Statistics for Economics
Management & Finance
Management
HR Managament
Income Tax
Finance
Economics
UPSC Study Material
Polity Notes
Geography Notes
History Notes
Science and Technology Notes
Economy Notes
Ethics Notes
Previous Year Papers
SSC/ BANKING
SSC CGL Syllabus
SBI PO Syllabus
SBI Clerk Syllabus
IBPS PO Syllabus
IBPS Clerk Syllabus
SSC CGL Practice Papers
Colleges
Indian Colleges Admission & Campus Experiences
List of Central Universities – In India
Colleges in Delhi University
IIT Colleges
NIT Colleges
IIIT Colleges
Companies
IT Companies
Software Development Companies
Artificial Intelligence(AI) Companies
CyberSecurity Companies
Service Based Companies
Product Based Companies
PSUs for CS Engineers
Preparation Corner
Company Wise Preparation
Preparation for SDE
Experienced Interviews
Internship Interviews
Competitive Programming
Aptitude Preparation
Puzzles
Exams
JEE Mains
JEE Advanced
GATE CS
NEET
UGC NET
More Tutorials
Software Development
Software Testing
Product Management
SAP
SEO – Search Engine Optimization
Linux
Excel
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Go To TopJavatpoint Logo

Home
C++
C
C#
Java
PHP
HTML
CSS
JavaScript
jQuery
XML
JSON
Ajax
Node.js
SQL
Projects
Interview Q
C++ Overloading (Function and Operator)
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:

Methods,
Constructors, and
Indexed properties
It is because these members have parameters only.

ADVERTISEMENT
Types of overloading in C++ are:
Function overloading
Operator overloading
C++ Overloading
C++ Function Overloading
ADVERTISEMENT
Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++. In function
overloading, the function is redefined by using either different types of arguments or a different
number of arguments. It is only through these differences compiler can differentiate between the
functions.

The advantage of Function overloading is that it increases the readability of the program because
you don’t need to use different names for the same action.

ADVERTISEMENT
C++ Function Overloading Example
Let’s see the simple example of function overloading where we are changing number of
arguments of add() method.

// program of function overloading when number of arguments vary.

#include <iostream>
Using namespace std;
Class Cal {
Public:
Static int add(int a,int b){
Return a + b;
}
Static int add(int a, int b, int c)
{
Return a + b + c;
}
};
Int main(void) {
Cal C; // class object declaration.
Cout<<C.add(10, 20)<<endl;
Cout<<C.add(12, 20, 23);
Return 0;
}
ADVERTISEMENT
Output:

30
55
Let’s see the simple example when the type of the arguments vary.

// Program of function overloading with different types of arguments.

ADVERTISEMENT
#include<iostream>
Using namespace std;
Int mul(int,int);
Float mul(float,int);

Int mul(int a,int b)


{
Return a*b;
}
Float mul(double x, int y)
{
Return x*y;
}
Int main()
{
Int r1 = mul(6,7);
Float r2 = mul(0.2,3);
Std::cout << “r1 is : “ <<r1<< std::endl;
Std::cout <<”r2 is : “ <<r2<< std::endl;
Return 0;
}
Output:

ADVERTISEMENT
R1 is : 42
R2 is : 0.6
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked among the overloaded
function, this situation is known as function overloading.

When the compiler shows the ambiguity error, the compiler does not run the program.

ADVERTISEMENT
Causes of Function Overloading:

Type Conversion.
Function with default arguments.
Function with pass by reference.
C++ Overloading
Type Conversion:
ADVERTISEMENT
Let’s see a simple example.

#include<iostream>
Using namespace std;
Void fun(int);
Void fun(float);
Void fun(int i)
{
Std::cout << “Value of i is : “ <<i<< std::endl;
}
Void fun(float j)
{
Std::cout << “Value of j is : “ <<j<< std::endl;
}
Int main()
{
Fun(12);
Fun(1.2);
Return 0;
}
The above example shows an error “call of overloaded ‘fun(double)’ is ambiguous”. The fun(10)
will call the first function. The fun(1.2) calls the second function according to our prediction.
But, this does not refer to any function as in C++, all the floating point constants are treated as
double not as a float. If we replace float to double, the program works. Therefore, this is a type
conversion from float to double.

ADVERTISEMENT
Function with Default Arguments
Let’s see a simple example.

#include<iostream>
Using namespace std;
Void fun(int);
Void fun(int,int);
Void fun(int i)
{
Std::cout << “Value of i is : “ <<i<< std::endl;
}
Void fun(int a,int b=9)
{
Std::cout << “Value of a is : “ <<a<< std::endl;
Std::cout << “Value of b is : “ <<b<< std::endl;
}
Int main()
{
Fun(12);

Return 0;
}
The above example shows an error “call of overloaded ‘fun(int)’ is ambiguous”. The fun(int a,
int b=9) can be called in two ways: first is by calling the function with one argument, i.e.,
fun(12) and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i)
function is invoked with one argument. Therefore, the compiler could not be able to select
among fun(int i) and fun(int a,int b=9).

Function with pass by reference


Let’s see a simple example.

#include <iostream>
Using namespace std;
Void fun(int);
Void fun(int &);
Int main()
{
Int a=10;
Fun(a); // error, which f()?
Return 0;
}
Void fun(int x)
{
Std::cout << “Value of x is : “ <<x<< std::endl;
}
Void fun(int &b)
{
Std::cout << “Value of b is : “ <<b<< std::endl;
}
The above example shows an error “call of overloaded ‘fun(int&)’ is ambiguous”. The first
function takes one integer argument and the second function takes a reference parameter as an
argument. In this case, the compiler does not know which function is needed by the user as there
is no syntactical difference between the fun(int) and fun(int &).

C++ Operators Overloading


Operator overloading is a compile-time polymorphism in which the operator is overloaded to
provide the special meaning to the user-defined data type. Operator overloading is used to
overload or redefines most of the operators available in C++. It is used to perform the operation
on the user-defined data type. For example, C++ provides the ability to add the variables of the
user-defined data type that is applied to the built-in data types.

The advantage of Operators overloading is to perform different operations on the same operand.

Operator that cannot be overloaded are as follows:


Scope operator (:
Sizeof
Member selector(.)
Member pointer selector(*)
Ternary operator(?:)
Syntax of Operator Overloading
Return_type class_name : : operator op(argument_list)
{
// body of the function.
}
Where the return type is the type of value returned by the function.

Class_name is the name of the class.

Operator op is an operator function where op is the operator being overloaded, and the operator
is the keyword.

Rules for Operator Overloading


Existing operators can only be overloaded, but the new operators cannot be overloaded.
The overloaded operator contains atleast one operand of the user-defined data type.
We cannot use friend function to overload certain operators. However, the member function can
be used to overload those operators.
When unary operators are overloaded through a member function take no explicit arguments,
but, if they are overloaded by a friend function, takes one argument.
When binary operators are overloaded through a member function takes one explicit argument,
and if they are overloaded through a friend function takes two explicit arguments.
C++ Operators Overloading Example
Let’s see the simple example of operator overloading in C++. In this example, void operator ++
() operator function is defined (inside Test class).

// program to overload the unary operator ++.

#include <iostream>
Using namespace std;
Class Test
{
Private:
Int num;
Public:
Test(): num(8){}
Void operator ++() {
Num = num+2;
}
Void Print() {
Cout<<”The Count is: “<<num;
}
};
Int main()
{
Test tt;
++tt; // calling of a function “void operator ++()”
tt.Print();
return 0;
}
Output:

The Count is: 10


Let’s see a simple example of overloading the binary operators.

// program to overload the binary operators.

#include <iostream>
Using namespace std;
Class A
{

Int x;
Public:
A(){}
A(int i)
{
X=i;
}
Void operator+(A);
Void display();
};

Void A :: operator+(A a)
{

Int m = x+a.x;
Cout<<”The result of the addition of two objects is : “<<m;

}
Int main()
{
A a1(5);
A a2(4);
A1+a2;
Return 0;
}
Output:

The result of the addition of two objects is : 9

← PrevNext →

Youtube For Videos Join Our Youtube Channel: Join Now


Feedback
Send your Feedback to feedback@javatpoint.com
Help Others, Please Share
Facebook twitter pinterest

Learn Latest Tutorials


Splunk tutorial
Splunk
SPSS tutorial
SPSS

Swagger tutorial
Swagger

T-SQL tutorial
Transact-SQL

Tumblr tutorial
Tumblr

React tutorial
ReactJS

Regex tutorial
Regex

Reinforcement learning tutorial


Reinforcement Learning

R Programming tutorial
R Programming

RxJS tutorial
RxJS
React Native tutorial
React Native

Python Design Patterns


Python Design Patterns

Python Pillow tutorial


Python Pillow

Python Turtle tutorial


Python Turtle

Keras tutorial
Keras

Preparation
Aptitude
Aptitude

Logical Reasoning
Reasoning

Verbal Ability
Verbal Ability

Interview Questions
Interview Questions

Company Interview Questions


Company Questions

Trending Technologies
Artificial Intelligence
Artificial Intelligence

AWS Tutorial
AWS

Selenium tutorial
Selenium

Cloud Computing
Cloud Computing

Hadoop tutorial
Hadoop

ReactJS Tutorial
ReactJS

Data Science Tutorial


Data Science
Angular 7 Tutorial
Angular 7

Blockchain Tutorial
Blockchain

Git Tutorial
Git

Machine Learning Tutorial


Machine Learning

DevOps Tutorial
DevOps

B.Tech / MCA
DBMS tutorial
DBMS

Data Structures tutorial


Data Structures

DAA tutorial
DAA
Operating System
Operating System

Computer Network tutorial


Computer Network

Compiler Design tutorial


Compiler Design

Computer Organization and Architecture


Computer Organization

Discrete Mathematics Tutorial


Discrete Mathematics

Ethical Hacking
Ethical Hacking

Computer Graphics Tutorial


Computer Graphics

Software Engineering
Software Engineering

Html tutorial
Web Technology
Cyber Security tutorial
Cyber Security

Automata Tutorial
Automata

C Language tutorial
C Programming

C++ tutorial
C++

Java tutorial
Java

.Net Framework tutorial


.Net

Python tutorial
Python

List of Programs
Programs

Control Systems tutorial


Control System
Data Mining Tutorial
Data Mining

Data Warehouse Tutorial


Data Warehouse

ADVERTISEMENT
X

Open In App

GEEKSFORGEEKS
C++ Bit Fields
When we declare the members in a struct and classes, a pre-determined size is allocated for the
member variables. In C++, we can compress that allocated size using bit fields.

Bit Field is a feature in C++ for specifying the size of struct and class members so that they
occupy a specific number of bits, not the default memory size.

For example, an integer takes 4 bytes of size but this size is large according to our requirements
so we can change it to 2 bytes using bit fields.

Syntax of Bit Field in C++


In C++, we can define a bit field by specifying the data type and then the field name with the
desired width in bits.
Bit-Field Syntax in Struct
Struct StructName {
dataType fieldName : width;
// more bit-field members...
};
Bit-Field Syntax in Classes
Class ClassName {
Public:
dataType fieldName : width;
// more bit-field members...
};
Where width is the number of bits.

Note: It is to be noted that bit fields are only acceptable for integral data types.

Example of C++ Bit Fields


The following examples demonstrate the use of bit fields in both structures and classes.

Example 1: Bit Fields in Structures


In the below example, we will compare the size difference between the structure that does not
specify bit fields and the structure that has specified bit fields.

// C++ program to demonstrate the size occupied by a struct


// with and without bitfields
#include <iostream>
Using namespace std;

// Define a struct without bit fields

Struct Loan1 {

Unsigned int principal;

Unsigned int interestRate;

Unsigned int period;


};

// Define a struct with bit-fields

Struct Loan2 {

// principal variable can store maximum value of

// 1,048,575

Unsigned int principal : 20;

// Maximum interest rate of 63

Unsigned int interestRate : 6;


// Maximum period of 63 months

Unsigned int period : 6;


};

Int main()
{

// printing the size of both structures

Cout << “Size of Structure without Bit Fields: “;

Cout << sizeof(Loan1) << “ Bytes” << endl;

Cout << “Size of Structure with Bit Fields: “;

Cout << sizeof(Loan2) << “ Bytes” << endl;

Return 0;
}
Output
Size of Structure without Bit Fields: 12 Bytes
Size of Structure with Bit Fields: 4 Bytes
Explanation
For the structure ‘Loan’, the size is 12 bytes which accounts for 4 bytes for each of the three
integer members.
In structure ‘Loan2″, we have used bit fields to specify the memory allocated to the member
variables of a struct in bits.
We have specified 20 bits for ‘principal’, 6 bits for ‘interest rate’, and 6 bits for ‘period’.
They all contributed to 32 bits which is equal to 4 Bytes which is why the size of ‘Loan2″ is 4
bytes.
Example 2: Class with Bit Fields in C++
In the below example, we have used bit fields with classes instead of struct.

// C++ program to demonstrate the size occupied by a class


// by specifying the bits to member variables of the class
// using bit fields
#include <iostream>

Using namespace std;

// Define a class with bit-fields for loan information

Class Loan {

Public:

// Maximum principal of 1,048,575

Unsigned int principal : 20;

// Maximum interest rate of 63

Unsigned int interestRate : 6;


// Maximum period of 63 months

Unsigned int period : 6;


};

Int main()
{

Loan loan1;

Loan1.principal = 500000;

Loan1.interestRate = 15;

Loan1.period = 36;

// Print the size of loan1

// (20+6+6)/8 = 4 Bytes

// 1 Byte = 8 Bits

Cout << sizeof(Loan) << “ Bytes” << endl;


Return 0;
}
Output
4 Bytes
Explanation
In the above example, we have used bit fields to specify the memory allocated to the member
variables of a class in bits. We have specified 20 bits for ‘principal’, 6 bits for ‘interest rate’, and
6 bits for ‘period’. They all contributed to 32 bits which is equal to 4 Bytes.

Some Interesting Facts about Bit Fields


1. The number of bits assigned to a member variable can be greater than the default size of
the data type of variable.
// C++ program to demonstrate that the number of bits
// assigned to a member variablecan be greater than the
// default size of the data type of variable.
#include <bits/stdc++.h>

Using namespace std;

// Define a structure with bit fields

Struct values {

Int num : 520;


};
Int main()
{

Values val1;

// Assigning value to num variable

Val1.num = 1;

// Print the size of struct

Cout << sizeof(val1) << “ Bytes” << endl;

Return 0;
}
Output
80 Bytes
Explanation
The num variable is assigned 520 bits, which (assuming a 32-bit or 4-byte int) would require
16.25 ints or 65 bytes to represent. Rounding up it to the upper limit of 17, 17*32 bits=544 bits
would have been enough to store the requested value, but compiler padding and alignment issues
push the allotment to 80 bytes i.e. 640 bits or 20 ints.

2. We can not create pointers that point to bit fields because they might not start at a byte
boundary.
// C++ program to demonstrate that we can not create
// pointers that points to bit fields
#include <iostream>

Using namespace std;

Struct BitField {

Unsigned int num : 1;


};

Int main()
{

BitField var;

Var.num = 1;

// Error: Cannot take the address of a bit field

// unsigned

Unsigned int* ptr = &var.num;

// Error: Cannot create a reference to a bit field


Int& ref = var.num;

Cout << var.num << endl;

Return 0;
}
Output

./Solution.cpp: In function ‘int main()’:


./Solution.cpp:15:30: error: attempt to take address of bit-field structure member ‘BitField::num’
Unsigned int* ptr = &var.num;
^
./Solution.cpp:18:20: error: invalid initialization of non-const reference of type ‘int&’ from an
rvalue of type ‘int’
Int& ref = var.num;
^
Applications of Bit Fields in C++
It is majorly used for memory optimization as it allows us to use only the necessary number of
bits to represent a member variable which reduces memory overhead.
It can be used to compress the data so that it can take less time to transfer data from one point to
another over the network.
It can be used to design hardware registers that have specific bit structures.
In graphics applications, color components, pixel formats, and image data often have specific bit
requirements which can be customized using bit fields.
Article Tags : C++ CPP-Basics
Recommended Articles
1. How to compile 32-bit program on 64-bit gcc in C and C++
2. Longest Increasing Subsequence using BIT
3. C++ Program to Check if two numbers are bit rotations of each other or not
4. Find a Mother vertex in a Graph using Bit Masking
5. Generate n-bit Gray Codes | Set 2
Read Full Article
A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh – 201305
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Apply for Mentor
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
Tutorials Archive
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
Top 100 DSA Interview Problems
DSA Roadmap by Sandeep Jain
All Cheat Sheets
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
HTML & CSS
HTML
CSS
Web Templates
CSS Frameworks
Bootstrap
Tailwind CSS
SASS
LESS
Web Design
Python
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Python Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
Competitive Programming
Top DS or Algo for CP
Top 50 Tree
Top 50 Graph
Top 50 Array
Top 50 String
Top 50 DP
Top 15 Websites for CP
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
JavaScript
JavaScript Examples
TypeScript
ReactJS
NextJS
AngularJS
NodeJS
Lodash
Web Browser
NCERT Solutions
Class 12
Class 11
Class 10
Class 9
Class 8
Complete Study Material
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Indian Economics
Macroeconomics
Microeconimics
Statistics for Economics
Management & Finance
Management
HR Managament
Income Tax
Finance
Economics
UPSC Study Material
Polity Notes
Geography Notes
History Notes
Science and Technology Notes
Economy Notes
Ethics Notes
Previous Year Papers
SSC/ BANKING
SSC CGL Syllabus
SBI PO Syllabus
SBI Clerk Syllabus
IBPS PO Syllabus
IBPS Clerk Syllabus
SSC CGL Practice Papers
Colleges
Indian Colleges Admission & Campus Experiences
List of Central Universities – In India
Colleges in Delhi University
IIT Colleges
NIT Colleges
IIIT Colleges
Companies
IT Companies
Software Development Companies
Artificial Intelligence(AI) Companies
CyberSecurity Companies
Service Based Companies
Product Based Companies
PSUs for CS Engineers
Preparation Corner
Company Wise Preparation
Preparation for SDE
Experienced Interviews
Internship Interviews
Competitive Programming
Aptitude Preparation
Puzzles
Exams
JEE Mains
JEE Advanced
GATE CS
NEET
UGC NET
More Tutorials
Software Development
Software Testing
Product Management
SAP
SEO – Search Engine Optimization
Linux
Excel
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

You might also like