2 C++
2 C++
2 C++
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.
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().
Class Geeks {
// Access specifier
Public:
// Data Members
String geekname;
// Member Functions()
Int main()
{
Geeks obj1;
Obj1.geekname = “Abhi”;
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.
#include <bits/stdc++.h>
Class Geeks
{
Public:
String geekname;
Int id;
Void printname();
// printid is defined inside class definition
Void printid()
}
};
Void Geeks::printname()
{
Int main() {
Geeks obj1;
Obj1.geekname = “xyz”;
Obj1.id=15;
// call printname()
Obj1.printname();
// 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>
Class Geeks
{
Public:
Int id;
//Default Constructor
Geeks()
Id=-1;
//Parameterized Constructor
Geeks(int x)
Id=x;
}
};
Int main() {
Geeks obj1;
Geeks obj2(21);
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 Geeks
{
Public:
Int id;
~Geeks()
{
}
};
Int main()
Geeks obj1;
Obj1.id=7;
Int i = 0;
While ( i < 5 )
Geeks obj2;
Obj2.id=i;
I++;
Return 0;
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:
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>
Class Demo{
Public:
Int a, b;
Demo()
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
Skip to content
PrepBytes Blog
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.
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.
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.
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.
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;
}
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
[email protected]
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
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.
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;
}
};
Int main ()
{
// create object for the class Car
Car c1;
// call inp() function to insert values
C1. Inp ();
C1. Disp();
ADVERTISEMENT
Enter the Id of the Car:
101
Enter the name of the Car:
Ferrari
Number of the Marks (1 – 10):
10
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
#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;
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
SPSS tutorial
SPSS
Swagger tutorial
Swagger
T-SQL tutorial
Transact-SQL
Tumblr tutorial
Tumblr
React tutorial
ReactJS
Regex tutorial
Regex
R Programming tutorial
R Programming
RxJS tutorial
RxJS
Keras tutorial
Keras
Preparation
Aptitude
Aptitude
Logical Reasoning
Reasoning
Verbal Ability
Verbal Ability
Interview Questions
Interview Questions
Trending Technologies
Artificial Intelligence
Artificial Intelligence
AWS Tutorial
AWS
Selenium tutorial
Selenium
Cloud Computing
Cloud Computing
Hadoop tutorial
Hadoop
ReactJS Tutorial
ReactJS
Angular 7 Tutorial
Angular 7
Blockchain Tutorial
Blockchain
Git Tutorial
Git
DevOps Tutorial
DevOps
B.Tech / MCA
DBMS tutorial
DBMS
DAA tutorial
DAA
Operating System
Operating System
Software Engineering
Software Engineering
Html tutorial
Web Technology
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
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:
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
Class Employee
{
Int id;
Char name[30];
Public:
Cout<<”Enter Id : “;
Cin>>id;
Cout<<”Enter Name : “;
Cin>>name;
}
Cout<<id<<” “;
Cout<<name<<” “;
Cout<<endl;
}
Int main(){
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-
Class Employee
{
Int id;
Char name[30];
Public:
// Declaration of function
Void getdata();
// Declaration of function
Void putdata();
};
Void Employee::getdata()
{
// Driver code
Int main()
{
Employee emp[30];
Int n, i;
Cin >> n;
// Accessing the function
Emp[i].getdata();
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:
Class item
{
Char name[30];
Int price;
Public:
Void getitem();
Void printitem();
};
// Function to get item details
Void item::getitem()
{
“\n”;
“\n”;
}
// Driver code
Int main()
{
Item t[size];
(i + 1) << “\n”;
T[i].getitem();
(i + 1) << “\n”;
T[i].printitem();
}
}
Output:
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.
Syntax:
Friend class
Example:
Private:
Int private_variable;
Protected:
Int protected_variable;
Public:
GFG()
Private_variable = 10;
Protected_variable = 99;
Class F {
Public:
Void display(GFG& t)
<< 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.
Syntax:
Example:
Private:
Int private_variable;
Protected:
Int protected_variable;
Public:
Base()
Private_variable = 10;
Protected_variable = 99;
}
// friend function declaration
<< endl;
// 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.
Example:
Class anotherClass {
Public:
Class base {
Private:
Int private_variable;
Protected:
Int protected_variable;
Public:
Base()
Private_variable = 10;
Protected_variable = 99;
<< endl;
// 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.
// 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;
Else
// Driver code
Int main()
{
ABC _abc;
XYZ _xyz;
_xyz.set_data(20);
_abc.set_data(35);
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++:
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.
#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.
ADVERTISEMENT
#include<iostream>
Using namespace std;
Int mul(int,int);
Float mul(float,int);
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).
#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 &).
The advantage of Operators overloading is to perform different operations on the same operand.
Operator op is an operator function where op is the operator being overloaded, and the operator
is the keyword.
#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:
#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:
← PrevNext →
Swagger tutorial
Swagger
T-SQL tutorial
Transact-SQL
Tumblr tutorial
Tumblr
React tutorial
ReactJS
Regex tutorial
Regex
R Programming tutorial
R Programming
RxJS tutorial
RxJS
React Native tutorial
React Native
Keras tutorial
Keras
Preparation
Aptitude
Aptitude
Logical Reasoning
Reasoning
Verbal Ability
Verbal Ability
Interview Questions
Interview Questions
Trending Technologies
Artificial Intelligence
Artificial Intelligence
AWS Tutorial
AWS
Selenium tutorial
Selenium
Cloud Computing
Cloud Computing
Hadoop tutorial
Hadoop
ReactJS Tutorial
ReactJS
Blockchain Tutorial
Blockchain
Git Tutorial
Git
DevOps Tutorial
DevOps
B.Tech / MCA
DBMS tutorial
DBMS
DAA tutorial
DAA
Operating System
Operating System
Ethical Hacking
Ethical Hacking
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
Python tutorial
Python
List of Programs
Programs
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.
Note: It is to be noted that bit fields are only acceptable for integral data types.
Struct Loan1 {
Struct Loan2 {
// 1,048,575
Int main()
{
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.
Class Loan {
Public:
Int main()
{
Loan loan1;
Loan1.principal = 500000;
Loan1.interestRate = 15;
Loan1.period = 36;
// (20+6+6)/8 = 4 Bytes
// 1 Byte = 8 Bits
Struct values {
Values val1;
Val1.num = 1;
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>
Struct BitField {
Int main()
{
BitField var;
Var.num = 1;
// unsigned
Return 0;
}
Output