C++ Access Modifiers Overview
Public:
• Class members declared under public specifier are accessible to all.
• Data members and member functions can be accessed by other classes and functions.
• Accessible from anywhere in the program using the direct member access operator (.).
// C++ program to demonstrate public
// access modifier
#include<iostream>
using namespace std;
// class definition
class Circle
public:
double radius;
double compute_area()
return 3.14*radius*radius;
};
// main function
int main()
Circle obj;
// accessing public datamember outside class
obj.radius = 5.5;
cout << "Radius is: " << obj.radius << "\n";
cout << "Area is: " << obj.compute_area();
return 0;
Output:
Radius is: 5.5
Area is: 94.985
Private:
• Class members declared as private can only be accessed by member functions inside
the class.
• Access to private data members of a class is restricted to member functions or friend
functions.
// C++ program to demonstrate private
// access modifier
#include<iostream>
using namespace std;
class Circle
// private data member
private:
double radius;
// public member function
public:
double compute_area()
{ // member function can access private
// data member radius
return 3.14*radius*radius;
};
// main function
int main()
// creating object of the class
Circle obj;
// trying to access private data member
// directly outside the class
obj.radius = 1.5;
cout << "Area is:" << obj.compute_area();
return 0;
Output:
In function 'int main()':
11:16: error: 'double Circle::radius' is private
double radius;
^
31:9: error: within this context
obj.radius = 1.5;
// C++ program to demonstrate private
// access modifier
#include<iostream>
using namespace std;
class Circle
// private data member
private:
double radius;
// public member function
public:
void compute_area(double r)
{ // member function can access private
// data member radius
radius = r;
double area = 3.14*radius*radius;
cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
};
// main function
int main()
// creating object of the class
Circle obj;
// trying to access private data member
// directly outside the class
obj.compute_area(1.5);
return 0;
}
Output:
Radius is: 1.5
Area is: 7.065
Protected:
• Similar to access modifier, protected access can be accessed by any subclass of that
class.
• Private data members of a class can be accessed indirectly using public member
functions.
// C++ program to demonstrate
// protected access modifier
#include <bits/stdc++.h>
using namespace std;
// base class
class Parent
// protected data members
protected:
int id_protected;
};
// sub class or derived class from public base class
class Child : public Parent
{
public:
void setId(int id)
// Child class is able to access the inherited
// protected data members of base class
id_protected = id;
void displayId()
cout << "id_protected is: " << id_protected << endl;
};
// main function
int main() {
Child obj1;
// member function of the derived class can
// access the protected data members of the base class
obj1.setId(81);
obj1.displayId();
return 0;
Output:
id_protected is: 81
C++ Friend Class and Function Definition
Friend Class Definition
• A friend class can access private and protected members of other
classes declared as a friend.
• The friend keyword is used to declare a friend class in C++.
// 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
Friend Function Definition
• A friend function can be granted special access to private and
protected members of a class.
• They are non-member functions that can access and manipulate the
private and protected members of the class.
• A friend function can be a global function or a member function of
another class.
// 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
Features of Friend Functions
• A friend function is a special function in C++ that can access the
private and protected data of a class.
• It is a non-member function or ordinary function of a class,
declared as a friend using the keyword “friend” inside the class.
• The keyword “friend” is placed only in the function declaration of
the friend function.
• A friend function can be declared in any section of the class i.e.,
public, private, or protected.
• Friend functions are special functions in C++ that can access
private and protected data of a class.
• They are non-member functions or ordinary functions of a class,
declared as a friend using the keyword "friend" inside the class.
• The keyword "friend" is placed only in the function declaration of
the friend function, not in the function definition or call.
• A friend function is called like an ordinary function and cannot be
called using the object name and dot operator.
• It can accept the object as an argument whose value it wants to
access.
// 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;
Output35
Friend Functions Advantages and Disadvantages
Advantages:
• Allows access to members without inheriting the class.
• Acts as a bridge between two classes.
• Increases versatility of overloaded operators.
• Can be declared in public or private or protected class parts.
Disadvantages:
• Violates data hiding law by accessing private class members.
• Cannot perform run-time polymorphism in members.
C++ Constructor Overview
• Constructor is a member function of a class, invoked automatically
at object creation.
• It initializes data members of new objects.
• The constructor's name is the same as the class name.
• It constructs values, providing data for the object.
• Constructors do not return values, hence they do not have a return
type.
• They are called automatically when creating the class object.
• They can be overloaded and cannot be declared virtual.
• The constructor prototype is (list-of-parameters).
• Constructors can be defined inside or outside the class declaration.
Syntax of Constructors in C++
The prototype of the constructor looks like this:
<class-name> (list-of-parameters);
The constructor can be defined inside the class declaration or outside the class
declaration
Syntax for Defining the Constructor Within the Class
<class-name> (list-of-parameters)
{
// constructor definition
}
Syntax for Defining the Constructor Outside the Class
<class-name>: :<class-name>(list-of-parameters)
{
// constructor definition
}
// defining the constructor within the class
#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;
public:
// constructor
student()
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
void display()
cout << endl << rno << "\t" << name << "\t" << fee;
};
int main()
student s; // constructor gets called automatically when
// we create the object of the class
s.display();
return 0;
Output
Enter the RollNo:121
Enter the Name:Geeks
Enter the Fee:5000
121 Geeks 5000
Example 2: Defining the Constructor Outside the Class
// defining the constructor outside the class
#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;
public:
// constructor declaration only
student();
void display();
};
// outside definition of constructor
student::student()
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
void student::display()
cout << endl << rno << "\t" << name << "\t" << fee;
// driver code
int main()
student s;
s.display();
return 0;
Output
Enter the RollNo:11
Enter the Name:Aman
Enter the Fee:10111
11 Aman 10111
C++ Constructor Characteristics
• Name of constructor is same as class name.
• Mostly declared in public or private class sections.
• Do not return values, hence no return type.
• Called automatically when class object is created.
• Cannot be overloaded, declared virtual, or inherited.
• Addresses of constructor cannot be referred to.
• Makes implicit calls to new and delete operators during memory
allocation.
Default Constructor in Java
• Default constructor is a constructor without arguments or default
value for every argument.
• Zero argument constructor or default constructor accepts no
arguments.
• If not defined in source code, default constructor is implicitly
defined by the compiler during compilation.
• If defined explicitly, default constructor is called implicitly by
the compiler.
• Default constructors are used to create objects without specific
initial values.
• If no constructors are explicitly declared, default constructor is
automatically provided by the compiler.
• A default constructor can contain default argument with default
values for an object.
• The compiler implicitly declares the default constructor and defines
it when needed.
• The default constructor is required for initializing class internals
and does not touch data members or data types.
// CPP program to demonstrate Default constructors
#include <iostream>
using namespace std;
class Base {
public:
// compiler "declares" constructor
};
class A {
public:
// User defined constructor
A() { cout << "A Constructor" << endl; }
// uninitialized
int size;
};
class B : public A {
// compiler defines default constructor of B, and
// inserts stub to call A constructor
// compiler won't initialize any data of A
};
class C : public A {
public:
C()
// User defined default constructor of C
// Compiler inserts stub to call A's constructor
cout << "C Constructor" << endl;
// compiler won't initialize any data of A
};
class D {
public:
D()
// User defined default constructor of D
// a - constructor to be called, compiler inserts
// stub to call A constructor
cout << "D Constructor" << endl;
// compiler won't initialize any data of 'a'
private:
A a;
};
// Driver Code
int main()
Base base;
B b;
C c;
D d;
return 0;
Output
A Constructor
A Constructor
C Constructor
A Constructor
D Constructor
"Copy Constructor Overview"
• Member function initializing an object using another of the same
class.
• Creates an object by copying members of an existing object.
• Used to initialize newly created object members.
Copy constructor takes a reference to an object of the same class as an
argument.
Sample(Sample &t)
{
id=t.id;
}
#include <iostream>
#include <string.h>
using namespace std;
class student {
int rno;
char name[50];
double fee;
public:
student(int, char[], double);
student(student& t) // copy constructor
rno = t.rno;
strcpy(name, t.name);
fee = t.fee;
void display();
};
student::student(int no, char n[], double f)
rno = no;
strcpy(name, n);
fee = f;
void student::display()
cout << endl << rno << "\t" << name << "\t" << fee;
int main()
student s(1001, "Manjeet", 10000);
s.display();
student manjeet(s); // copy constructor called
manjeet.display();
return 0;
Output1001 Manjeet 10000
1001 Manjeet 10000
Understanding Destructor in C++
Definition and Function of Destructor
• Destructor is an instance member function that is invoked
automatically when an object is destroyed.
• It is a special member function like a constructor, destroying class
objects created by the constructor.
• Destructor is the last function to be called before an object is
destroyed.
• It is not possible to define more than one destructor.
• Destructor is the only way to destroy the object created by the
constructor.
• It releases memory space occupied by the objects created by the
constructor.
• Objects are destroyed in the reverse order of their creation.
Syntax for Destructor Definition
• Destructor definition within the class: ~ () {
Private Destructors in C++
Understanding Private Destructors
• Private destructors prevent the destruction of an object.
• They are used to control the destruction of objects of a class.
Use of Private Destructors
• For dynamically created objects, the destructor is private.
• The destructor is not a compiler error, but it can be a problem when
the object is referred after the function call.
Programs Compiling with Private Destructors
• The above program compiles and runs fine, indicating that creating
private destructors is not a compiler error.
• The program fails in compilation due to the private nature of the
destructor.
Creation of Class Instances with Private Destructors
• In the case where the destructor is declared private, an instance of
the class can be created using the malloc() function.
• The function can only delete the objects of the class.
Using Class Instance Methods
• The class instance method can also be used to create classes with
private destructors.
• The function can only delete the objects of the class.
Copy Constructor in C++
• A copy constructor is a member function that initializes an object
using another object of the same class.
• It is called when a new object is created from an existing one, as a
copy of the existing one.
• In C++, a copy constructor is called when an object of the class is
returned by value, passed by value as an argument, an object is
constructed based on another object of the same class, initialization
lists with braces are used, or the compiler generates a temporary
object.
• Example scenarios include:
- Initialization with another object of the same type: The copy
constructor is called when an object is created by directly
initializing it with another object of the same type.
• The C++ Standard allows the compiler to optimize the copy away in
certain cases, such as Return Value Optimization (RVO).
Understanding Static Data Members in C++
Static Data Members
• Class members declared using static keywords.
• Only one copy of the member is created for the entire class and
shared by all objects.
• Initialized before any object of this class is created, even before
the main starts.
• Visible only within the class, but its lifetime is the entire
program.
Accessing a Static Member
• Static members are only declared in the class declaration, not
defined.
• Accessing a static data member without an explicit definition will
give an error.
• To access the static data member of any class, it must be defined
first.
Defining Static Data Member
• To access the static data member of any class, we must define it
first.
• Static data members can only be defined globally in C++.
Accessing Static Members Without Any Object
• Accessing any static member without any object can be done using the
scope resolution operator directly with the class name.
C++ static keywords and static members
Static Keywords in C++
• Used to make a variable's memory static once declared.
• Cannot be changed once declared.
Static Members in C++
• Not associated with class objects.
• Treat as same for all objects associated with the class.
• Can be called even if no class objects exist.
• Accessible using the class name through the scope resolution
operator.
• Can access static data members and static member functions inside or
outside of the class.
• Have a scope inside the class and cannot access the current object
pointer.
Static Member Functions in C++
• Independent of any object of the class.
• Can be called even if no class objects exist.
• Can access static data members and static member functions inside or
outside of the class.
• Can determine how many objects of the class have been created.
Requirement of Static Member Functions
• Used to store information shared by all objects in a class.
• Can be used to track the quantity of newly generated objects of a
specific class type.
Understanding 'This' Pointer in C++
Objects and Functions
• Each object has its own copy of the data member.
• All objects share a single copy of member functions.
Access and Update of Data Members
• The compiler supplies an implicit pointer along with the names of
the functions as 'this'.
• The 'this' pointer is passed as a hidden argument to all nonstatic
member function calls and is available as a local variable within the
body of all nonstatic functions.
• The type of this pointer is 'X*' for a class X and 'const X *' for a
member function of X declared as const.
C++'s Early Versions and Current Use
• The early version of C++ allowed 'this' pointer to be changed,
allowing a programmer to change which object a method was working on.
• This feature was later removed, and now 'this' is an r-value.
Status of 'This' Pointer Usage
• When local variable’s name is the same as a member’s name.
• To return reference to the calling object.
• When a reference to a local object is returned, the returned
reference can be used to chain function calls on a single object.
Exercise: Predicting Output of Programs
• The exercise involves predicting the output of the following
programs and fixing compilation errors.
C++ Program Overview: Scope Resolution Operator and Pointer
• Scope resolution operator is used to access static or class members.
• Pointer is used to access object members when there is a local
variable with the same name.
• The output in the program is 3 because the argument to the function
shadows the class's "a".
• The pointer can be used to output the class's "a" as it points to
the object from where the function is called.
• The scope resolution operator can only be used for static data
members or class members.
• In C++, static members must be explicitly defined.
• The pointer can be used to access static members when there is a
local variable with the same name.
Encapsulation in C++: A Real-Life Example
Definition and Application
• Encapsulation in C++ is the wrapping up of data and information in a
single unit.
• In Object Oriented Programming, it is defined as binding together
the data and the functions that manipulate them.
Real-Life Example
• In a company, different sections like accounts, finance, and sales
are wrapped under a single name.
• An official from the finance section needs data about sales in a
particular month, but must contact another officer in the sales
section.
Key Properties of Encapsulation
• Data Protection: Encapsulation keeps its data members private,
ensuring controlled and secure data manipulation.
• Information Hiding: Encapsulation hides the internal implementation
details of a class from external code.
Features of Encapsulation
• Access to functions from the class directly requires an object to
access that function that is using the member variables of that class.
• Encapsulation improves readability, maintainability, and security by
grouping data and methods together.
• It helps control the modification of our data members.
Simple Example of C++
• In C++, encapsulation can be implemented using classes and access
modifiers.
• The example shows that the data of the sections like sales, finance,
or accounts are hidden from any other section.
Data Abstraction in C++ Programming
• Data abstraction is a crucial feature of object-oriented programming
in C++.
• It involves displaying only essential information about the data and
hiding the details.
• Abstraction is akin to a car driver understanding the inner
mechanism of a car, but not the implementation.
Types of Abstraction
• Data abstraction: Shows only required information about the data and
hides unnecessary data.
• Control abstraction: Shows only required information about the
implementation and hides unnecessary information.
Abstraction in C++
• Abstraction can be implemented using classes, which group data
members and member functions using available access specifiers.
• Header files can also be used for abstraction.
Abstraction using Access Specifiers
• Access specifiers enforce restrictions on class members.
• Members declared as public in a class can be accessed from anywhere
in the program, while members declared as private can only be accessed
within the class.
Examples of Abstraction
• In a C++ program, the variables a and b are not allowed to be
directly accessed.
• The program also includes a class Vehicle with private and public
members.
Advantages of Data Abstraction
• Helps the user avoid writing low-level code.
• Avoids code duplication and increases reusability.
• Can change the internal implementation of the class.
S.NO: Abstraction vs Encapsulation
• Abstraction: Process of gaining information, encapsulation: Method
to contain information.
• Abstraction: Problems solved at design or interface level,
encapsulation at implementation level.
• Encapsulation: Method to hide unwanted information, protect
information from outside.
• Abstraction: Implemented using abstract classes and interfaces,
encapsulation using access modifiers.
• Abstraction: Implementation complexities hidden using abstract
classes and interfaces.
• Encapsulation: Objects aiding abstraction are encapsulated,
encapsulated objects are not.
C++ Polymorphism Overview
Definition and Examples
• Polymorphism refers to the ability of a message to be displayed in
multiple forms.
• It is a key feature of Object-Oriented Programming.
Types of Polymorphism
• Compile-time Polymorphism: Achieved by function overloading or
operator overloading.
• Function Overloading: Resulting from multiple functions with the
same name but different parameters.
• Examples include functions with 1 int parameter, 1 double parameter,
and 2 int parameters.
Explanation
• Function overloading is a feature of object-oriented programming.
• It involves changing the number of arguments or the type of
arguments.
• Examples include functions with different parameters, such as
func(), which acts differently in three different situations.
Operator Overloading in C++
• C++ allows operators to have a special meaning for a data type,
known as operator overloading.
• An example is the addition operator (+) for string class, which adds
two operands.
• The operator '+' is automatically called when '+' is used between
two Complex objects.
• The example program uses the operator '+' to perform the addition of
two numbers, not just adding them.
Function Overriding in C++: An Overview
• Function overriding in C++ is the redefinition of a base class
function in its derived class.
• It falls under the category of Runtime Polymorphism.
• Real-life examples of function overriding include the Constitution
of India and the relationship between RBI and other state banks.
• Function overriding can be demonstrated by calling the overridden
function of a member function from the child class.
• Variations in function overriding include calling the overridden
function using a pointer of Base type that points to an object of
Derived class, accessing overridden function to the Base Class using
the scope resolution operator, and accessing the overridden function.
• The defining of the Parent class and the derived class are crucial
in defining the overridden function and the derived class.
• The program also demonstrates accessing of overridden functions by
defining the Parent class and the derived class.
Function Overloading and Overriding Overview
• Fall under Compile-Time and Runtime Polymorphisms.
• Functions can be overloaded multiple times at Compile time.
• Functions cannot be overridden without inheritance at Runtime.
• Functions are in the same scope or different scopes.
Understanding Virtual Functions in C++
Understanding Virtual Functions
• Virtual functions are member functions declared in the base class
and re-defined in the derived class.
• They allow the compiler to perform late binding, matching the object
with the right-called function and executing it during runtime.
• This technique falls under Runtime Polymorphism, which refers to the
ability to take many forms in a hierarchy of classes related by
inheritance.
C++ Virtual Functions
• In C++, calling a virtual function could cause a different function
to be executed depending on the type of object invoked it.
• The virtual call mechanism is disallowed in constructors as
overriding from derived classes hasn't yet occurred.
• Objects are built from the ground up or follows a bottom to top
approach.
Example of Runtime Polymorphism
• The derived class’s function is called using a base class pointer.
• Virtual functions are called according to the type of the object
instance pointed to or referenced, not the type of the pointer or
reference.
• In this example, the get_Area() function of the base class is called
instead of the respective get_Area() functions of the child classes.
C++ Program to Calculate the Area of Shapes using Virtual Function
• The program uses the virtual constructor and virtual Destuctor to
avoid memory leaks.
Differences Between Inheritance and Polymorphism
• Inheritance creates a new class that inherits features from an
existing class.
• Polymorphism can be defined in multiple forms and is applied to
classes.
• Inheritance supports reusability and reduces code length in object-
oriented programming.
• Polymorphism allows the object to decide which form of the function
to implement at compile-time and run-time.
• Inheritance can be single, hybrid, multiple, hierarchical, and
multilevel.
• It's used in pattern designing.
• Example: Class bike can inherit from two-wheel vehicles class, which
can be a subclass of vehicles.
Function Overloading in C++
• Function overloading is a feature in object-oriented programming
where multiple functions have the same name but different parameters.
• It is a polymorphism feature in C++ where the function name should
be the same and the arguments should be different.
• It increases the readability of the program by allowing for only one
operation with the same name.
• Parameters should follow one or more conditions for Function
overloading:
- Parameters should have a different type (int a, int b)
- Parameters should have a different number (int a, int b, int c)
- Parameters should have a different sequence of parameters (int a,
double a, int b)
• If no match is found, C++ tries to find a match through the standard
conversion.
Constructor Overloading in C++
• Constructor overloading allows multiple constructors in a class with
the same name, but with different arguments.
• Overloaded constructors have the same name but differ by the number
and type of arguments.
• A constructor is called based on the number and type of arguments
passed.
• Arguments must be passed during object creation to indicate which
constructor needs to be called.
C++ Function Declarations and Overloading
• Function declarations differ only in the return type.
• Member function declarations with the same name and the name
parameter-type-list cannot be overloaded if any of them is a static
member function declaration.
• Parameter declarations differ only in a pointer * versus an array []
are equivalent.
• Parameter declarations differ only in that one is a function type
and the other is a pointer to the same function type are equivalent.
• Parameter declarations differ only in the presence or absence of
const and/or volatile are equivalent.
• Two parameter declarations that differ only in their default
arguments are equivalent.
Function Overloading and Namespaces
• Functions can be overload across namespaces.
• Namespaces can be introduced to the previous example without
drastically changing the source code.
Function Overloading in C++ Programming
• Function overloading is a feature where two or more functions can
have the same name but different parameters.
• It is a polymorphism feature in C++ where the function name is
overloaded with different jobs.
• Parameters should follow one or more of the following conditions for
Function overloading:
- Parameters should have a different type.
Function Overloading in C++ and Java
• Function overloading is possible in C++ and Java if the functions
differ by types and arguments in the argument list.
• Function overloading is not possible with different return types due
to compile-time polymorphism.
• The function signature is checked during compilation, allowing
functions to be overloaded if the signatures are different.
• The return type of a function does not affect function overloading,
so the same function signature with different return type will not be
overloaded.
• For example, two functions: int sum() and float sum(), will generate
a compile-time error as function overloading is not possible.
• C++ Program: CPP: Compiler error as it is a new declaration of
fun().
• Java Program: Compiler error as it is a new declaration of fun().
Function Overloading Advantages and Disadvantages
• Improves code readability and reusability.
• Saves memory space, consistency, and readability.
• Speeds up program execution.
• Enables easy code maintenance.
• Provides code flexibility.
• Eliminates need for different function names for same operations.
• Disadvantage: Function declarations differing only in return type
cannot be overloaded.
Operator Overloading in C++
Understanding Operator Overloading
• Operator overloading is a compile-time polymorphism in C++ that
gives special meaning to existing operators without changing their
original meaning.
• Examples include overloading an operator '+' in a class like String
to concatenate two strings.
• Other examples include overloading arithmetic operators in Complex
Numbers, Fractional Numbers, Big integers, etc.
Implementation of Operator Overloading
• Example: Adding two objects of type "class A" using the "+"
operator.
• The compiler generates an error as the addition operator is
predefined to only operate on built-in data types.
• The user redefines the meaning of the "+" operator to add two class
objects.
Difference between Operator Functions and Normal Functions
• Operator functions are the same as normal functions, but the name of
an operator function is always the operator keyword followed by the
operator symbol.
• Operator functions are called when the corresponding operator is
used.
Can We Overload All Operators?
• Almost all operators can be overloaded except a few.
Overloading Operators in C++
• Binary Arithmetic: +, -, *, /, %
• Unary Arithmetic: +, -, ++, —
• Assignment:=, +=,*=, /=,-=, %=
• Bitwise:&, |, <<, >>, ~, ^
• De-referencing:(->)
• Dynamic memory allocation,
• De-allocation:New, delete
• Subscript:[ ]
• Function call:()
• Logical:&, | |,!
• Relational:>, <, = =, <=, >=
Overloading Limitations
1. Sizeof Operator:
• Returns the size of the object or datatype entered as the operand.
• Cannot be evaluated during runtime.
2. Typeid Operator:
• Provides a CPP program with the ability to recover the derived type
of the object referred to by a pointer or reference.
3. Scope Resolution (::) Operator:
• Helps identify and specify the context to which an identifier refers
by specifying a namespace.
• Cannot be syntactically overloaded.
4. Class member access operators:
• Cannot be overloaded.
Overloading Unary and Binary Operators in C++
Unary Operator Overloading
• Operates on a single operand, requiring no arguments.
• Example: Distance class, which decrements the value of feet and
inches by 1 using a single operand.
• No argument is passed and no return_type value is returned.
Binary Operator Overloading
• Operates on two operands, requiring one argument.
• Example: Distance class, which adds two distance objects.
• Overloaded operator d3 is used to perform the addition of two
distance objects.
• Output: Total Feet & Inches: 18'11
Note: d2 = -d1 will not work as operator-() does not return any value.
C++ Functions and Functors
• Functions that take only one argument can be passed to using global
variables, but good coding practices advise against using them.
• Functors are objects that can be treated as functions or function
pointers.
• They are commonly used along with System.Tasks (STLs) in scenarios
like adding 1 to all elements of an array.
• Functors are used to handle the issue of multiple functions to add
each number, as they require a unary function for an array.
• A functor is a C++ class that acts like a function and is called
using the same old function call syntax.
• To create a functor, an object that overloads the operator() is
created.
• In this example, the function "increment" is a functor, a C++ class
that acts as a function.
• The code snippet shows how functors can be used in conjunction with
STLs.
Constructor in C++: A Class Member Function
• Constructor is a class member function that allocates memory for
class objects.
• It is automatically called when the object is created.
Multiple Inheritance in C++
• Multiple Inheritance allows a class to derive from several base
classes.
• The constructors of inherited classes are called in the same order
as they are inherited.
Syntax of Multiple Inheritance
• Example:
- class S: public A1, virtual A2
- A2(): base constructor
- S(): derived constructor
Example:
• The program implements constructor in multiple inheritance.
• The output includes the constructors of the base class A2, A1, and
the derived class S.