SlideShare a Scribd company logo
2
Declaration of pointers
• int *int_pointer; // pointer to an integer
• float *float_pointer; // pointer to a float
• double *double_pointer; // pointer to a double
• char *str; // pointer to a char or string
• int **ptrptr; // pointer to a pointer
3
Using Pointers in C++
1. We define a pointer variable
2. Assign the address of a variable to a pointer
3. Finally access the value at the address available in the pointer variable
• This is done by using the unary operator * that returns the value of the variable located at
the address specified by its operand
• int var = 20; // actual integer variable
• int *ip; // pointer to an integer variable declaration
• ip = &var; // store address of var in pointer variable
• cout<<ip<<endl; // print the address stored in ip pointer variable
• cout <<*ip<<endl; // access the value of the address available in pointer
• Dereferencing a pointer gives the value stored at the memory address
4
Example
5
Example
6
Example
7
Pointer Arithmetic
• Performing arithmetic operations on pointers
• Adding or subtracting an integer value to a pointer moves it to a
different memory location
• Increment/decrement pointers ( ++ or -- )
• (*ptr)++;
• “At the location pointed to by ptr, increment the value by 1.”
• Add/subtract an integer to/from a pointer ( + or += , - or -= )
• (*ptr)+=8;
• (*ptr)-=5;
The this Pointer
• The "this" pointer is a reserved pointer in C++ that points
to the current object.
• It allows objects to access their own members and
methods.
• In this example, the "this" pointer is used to print the
address of the current object.
When to Use "this"
Pointer
• You use the "this" pointer when there is a need to differentiate between class member
variables and function parameters with the same name.
• "this" pointer is particularly useful in situations where member variables and function
parameters share the same name, preventing confusion and enabling access to class
members.
• this->width = width; assigns the value of the width parameter (the one passed to the
setDimensions function) to the class member width. This effectively sets the width of the
rectangle.
• this->height = height; assigns the value of the height parameter (the one passed to the
setDimensions function) to the class member height. This effectively sets the height of the
rectangle.
Example
• The setName method is used to change the student's name. This method
demonstrates three different ways to access the name member variable:
• name = newName;: Here, we access the member variable directly.
• this->name = newName;: We use this-> to access the member variable
explicitly.
• (*this).name = newName;: We use (*this). to access the member
variable explicitly
Introduction to Function Templates
• So, what exactly are function templates? Function templates are a
way of writing functions that can work with multiple data types.
• They're like flexible blueprints for functions.
Function Overloading Recap
• Before we dive into function templates, let's briefly recap function
overloading.
• Function overloading allows us to have multiple functions with the
same name but different parameter lists.
• It's an important concept that forms the foundation for function templates.
Function Definition
• Define function header and function body
• Value-returning functions – int, double, char, float
return-data-type function-name(parameter list)
{
constant declarations
variable declarations
other C++ statements
return value
}
Function Definition (cont.)
• Non value-returning functions
void function-name(parameter list)
{
constant declarations
variable declarations
other C++ statements
}
Calling a function
• A function is called by specifying its name followed by its arguments.
• Non-value returning functions:
function-name (data passed to function);
• Value returning functions:
results = function-name (data passed to function);
int maxNum = maximum(4,67);
Advantages of using functions
• Functions can be called multiple times from different parts of the
program.
• Code can be reused, eliminating the need for redundant code and
saving time and effort.
• Functions simplify code maintenance by allowing changes in specific
functions instead of the entire program
Overloading
• Providing two or more different definitions of the same function name.
• Overloading a function: more than one function in the same class having the same name but
differing either in the number of parameters or the types of their parameters.
• The easiest way to remember this: the functions’ parameters should qualify any one or more than
one of the following conditions:
 They should have a different type.
 They should have a different number.
 They should have a different sequence of parameters.
We need to overload the function if we have to perform a single operation with different numbers or
types of arguments.
 Here’s a small function that you might write to find
the maximum of two integers.
int maximum(int a, int b)
{
if (a > b)
return a;
else
return b;
}
Finding the Maximum of Two Integers
 Here’s a small function that you might write to find
the maximum of two double numbers.
int maximum(double a, double b)
{
if (a > b)
return a;
else
return b;
}
Finding the Maximum of Two Doubles
Function Template
• Function templates are special functions that can operate with
generic types.
• Function templates allow the logic to be written once and used for all
data types – generic function.
• This allows us to create a function template whose functionality can
be adapted to multiple types or classes without repeating the entire
code for each type.
Function Template
• For example, a function to add two integer and float numbers requires two
functions.
• One function accepts integer types and the other accepts float types as
parameters even though the functionality is the same.
• Using a function template, a single function can be used to perform both
additions.
• It avoids unnecessary repetition of code for doing the same task on various
data types
• For each call, the compiler generates the complete function, replacing the
type parameter with the type or class to which the arguments belong.
Function Template Syntax
• A function template starts with the keyword
template
• Followed by template parameter(s) inside <>
which is followed by the function definition
• T is a template argument that accepts different
data types (int, float, etc.) and typename is a
keyword
• This 'T' can be replaced with any data type when we use the
template
• When an argument of a data type is passed to
functionname(), the compiler generates a new
version of functionname() for the given data
type
 This template function can be used with many data
types.
template <class Item>
Item maximum(Item a, Item b)
{
if (a > b)
return a;
else
return b;
}
A Template Function for Maximum
 A template prefix is also needed immediately
before the function’s implementation:
template <class Item>
Item maximum(Item a, Item b)
{
if (a > b)
return a;
else
return b;
}
A Template Function for Maximum
 Once a template function is defined, it may be used
with any adequate data type in your program...
template <class Item>
Item maximum(Item a, Item b)
{
if (a > b)
return a;
else
return b;
}
Using a Template Function
cout << maximum(1,2);
cout << maximum(1.3, 0.9);
...
Friend Function
• We have seen that private members can't be accessed from
outside class. Non member function cannot have access to the
private data of a class.
• Friend function: a function that is not a member of a class, but
has access to private members of the class
• A friend function can be a stand-alone function or a member
function of another class
• This function can be defined else where in the program.
• It can be declared either in the public or private part of a class
without affecting its meaning
• It is declared a friend of a class with the friend keyword in
the function prototype
11-26
Friend Function
• Friend functions of an object can "see" inside the object and access
private member functions and data.
• Syntax:
Friend returntype function_name(arguements);
Eg:
Friend void add();
A friend function has certain special characteristics:
1. It is not in the scope of class to which it has been declared as friend
2. Since it is not in the scope of class, it cannot be called using object
of that class
3. It can be invoked like a normal function without the help of any
object.
4. Unlike member function it can’t access member names directly and
has to use an object name and dot membership operator with each
member name
Access functions
• To allow clients to read the value
of private data, the class can
provide a get function.
• To allow clients to modify private
data, the class can provide a
set function.
Implementation of the Friend Function
Student &nm
Student &age
Operator Overloading
• If we want to make the operator ‘+’ add two class objects, we have to redefine the meaning of the ‘+’
such that it add two class objects
• We achieve this by using the concept of “Operator overloading”
• Redefining the meaning of operators does not change their original meaning
• It gives them additional meaning along with their existing ones
• Overloaded operators are functions with special names: the keyword "operator" followed by the
symbol for the operator being defined.
• Box operator+(const Box&);
• Declares the addition operator to add two Box objects and returns the final Box object
The syntax for C++ Operator Overloading
• To overload an operator, we use a special operator function
• The function is mostly defined inside the class or structure whose objects/variables we want the
overloaded operator to work with
• Here
• returnType is the return type of the function
• operator is a keyword
• symbol is the operator we want to overload
like: +, <, -, ++, etc.
• arguments is the arguments passed to the
function
Restrictions on Operator Overloading
• C++ operators that can be overloaded
• C++ Operators that cannot be overloaded
Operators that cannot be overloaded
. .* :: ?: sizeof
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
Rules of operator overloading
• We can overload an operator as its type only i.e., a unary operator cannot be overloaded as a binary
operator and vice versa.
• We can’t overload operators that are not a part of C++.
• At least one operand must be a user-defined class object
• We cannot change the operator’s existing functionality.
• When unary operators are overloaded through a member function, they do not take any explicit
arguments. But when overloaded by a friend function or non-member function, they take one
argument.
• When binary operators are overloaded through a member function, they take one explicit argument.
If overloaded through a friend function or non-member function, they instead take two explicit
arguments.
• There is a left-hand-side operand and a right-hand-side operand
• x ‘operator’ y (x+y or x*y), x is the left-hand-side operand and y is the right-hand-side operand
• The whole expression has a value after applying the operator
Ways of operator overloading
• Operator overloading of member functions.
• Operator overloading of non-member or friend functions.
Difference between Member and friend function
• Friend or non-member function:
• More parameters can be passed.
• Unary operators take one explicit parameter.
• Binary operators take two explicit parameters (need parameters for both operands)
• You can make the operator overloading function a friend function if it needs to access the
private and protected class members.
• If the left operand must be a built-in type or object of a different class, it must be a non-
member function
Non-member function Example
Difference between Member and friend function cont..
• Member function:
• The number of parameters to be passed is reduced by one, as the calling object is implicitly
supplied as an operand.
• The leftmost object must be of the same class as the operator
• Unary operators take no explicit parameters.
• Binary operators take only one explicit parameter.
• The operator overloading function may be a member function when the left operand is an
object of the Class.
Member Function - Example
Point result;
result.x = this->x + other.x;
result.y = this->y + other.y;
Overloading Types of Operators
• ++, -- operators overloaded differently for prefix vs. postfix notation
• Prefix notation
• Increment and decrement operators are placed before the operand (++obj, --obj)
• Overloaded increment/decrement operator returns the updated object after
incrementing or decrementing
• It performs the operation first, then returns the modified object
• Postfix notation
• Increment and decrement operators are placed after the operand (obj++, obj--)
• Overloaded increment/decrement operator returns a copy of the original object before
incrementing or decrementing
• It creates a temporary copy of the object, performs the operation on the original object,
then returns the copy
• Overloaded relational operators should return a bool value
• Overloaded stream operators >>, << must return istream,
ostream objects and take istream, ostream objects as
parameters
11-40
41
Stream Insertion and Extraction Operators as Global Functions
• Overload << operator used where
• Left operand of type ostream &
• Such as cout object in cout << classObject
• Overload >> has left operand of istream &
• Left operand of type istream &
• Such as cin object in cout >> classObject
• Reason:–
• These operators are associated with class of right operand
What Is Inheritance?
• Provides a way to create a new class from an existing class
• The new class is a specialized version of the existing class
42
The "is a" Relationship
• Inheritance establishes an "is a" relationship between classes.
– A poodle is a dog
– A car is a vehicle
– A flower is a plant
– A football player is an athlete
43
Inheritance
• Base class (or parent) – inherited from
• Derived class (or child) – inherits from the base class
• Notation:
class Student // base class
{
. . .
};
class UnderGrad : public student
{ // derived class
. . .
};
44
Back to the ‘is a’ Relationship
• An object of a derived class 'is a(n)' object of the base class
• Example:
• an UnderGrad is a Student
• a Mammal is an Animal
• A derived object has all of the characteristics of the base class
45
What Does a Child Have?
An object of the derived class has:
• all members defined in the child class
• these are the members unique to the derived class and not inherited from the parent class.
• All members declared in parent class
• all the members (both variables and functions) declared in the parent class. This includes public, protected, and private members,
but the access level depends on the inheritance type (public, protected, or private).
An object of the derived class can use:
• All public members defined in the child class
• All public members defined in the parent class
46
Class Access Specifiers
1) public – object of derived class can be treated as object of base
class (not vice-versa)
2) protected – more restrictive than public, but allows derived
classes to know details of parents
3) private – prevents objects of derived class from being treated as
objects of base class.
47
Inheritance vs. Access
48
private: x
protected: y
public: z
private: x
protected: y
public: z
private: x
protected: y
public: z
Base class members
x is inaccessible
private: y
private: z
x is inaccessible
protected: y
protected: z
x is inaccessible
protected: y
public: z
How inherited base class
members
appear in derived class
private
base class
protected
base class
public
base class
Inheritance vs. Access
49
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
class Test : public Grade
When Test class inherits
from Grade class using
public class access, it
looks like this:
private members:
int numQuestions:
float pointsEach;
int numMissed;
public members:
Test(int, int);
void setScore(float);
float getScore();
char getLetter();
Inheritance vs. Access
50
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
When Test class inherits
from Grade class using
protected class access, it
looks like this:
private members:
int numQuestions:
float pointsEach;
int numMissed;
public members:
Test(int, int);
protected members:
void setScore(float);
float getScore();
float getLetter();
class Test : protected Grade
Inheritance vs. Access
51
private members:
int numQuestions:
float pointsEach;
int numMissed;
void setScore(float);
float getScore();
float getLetter();
public members:
Test(int, int);
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
When Test class inherits
from Grade class using
private class access, it
looks like this:
class Test : private Grade
ExamRevision_FinalSession_C++ notes.pptx
Constructors and Destructors in Base and
Derived Classes
• Derived classes can have their own constructors and destructors
• When an object of a derived class is created, the base class’s
constructor is executed first, followed by the derived class’s
constructor
• When an object of a derived class is destroyed, its destructor is called
first, then that of the base class
53
Recursion
• Sometimes, the best way to solve a problem is by solving
a smaller version of the exact same problem first
• Recursion is a technique that solves a problem by solving
a smaller problem of the same type
• In programming recursion is a method call to the
same method. In other words, a recursive method
is one that calls itself.
• Recursive algorithms are simple to understand and
prove correct, easy to implement
• But! Recursive calls can result in an
infinite loop of calls
• Recursion needs a base case in
order to stop
Content of a Recursive Method
• Base case(s).
• There is a base case (or cases) that is tested
upon entry
• Values of the input variables for which
we perform no recursive calls are called
base cases (there should be at least
one base case).
• Every possible chain of recursive calls must
eventually reach a base case.
• Recursive calls.
• Calls to the current method.
• Each recursive call should be defined so that
it makes progress towards a base case.
How to write a recursive function?
• Determine the size factor
• how the problem size is reduced with each recursive call.
• Determine the base case(s)
• (the one for which you know the answer)
• When the base case is reached, the recursion stops.
• Determine the general case(s)
• (the one where the problem is expressed as a smaller
version of itself)
• Verify the algorithm
• (use the "Three-Question-Method") - next slide
Three-Question Verification Method
1. Does the function always reach the base case?
• Ensure that the recursion progress leads to the base case to prevent
infinite recursion
2. Does the function correctly solve the base case?
• Verify that the base case solution is correct.
3. Does the function correctly combine results of recursive
calls to solve the general case?
• Ensure that the recursive calls and their results are combined
accurately to solve the overall problem.
Recursion vs. iteration
• Iteration can be used in place of recursion
• An iterative algorithm uses a looping construct
• A recursive algorithm uses a branching structure
• Recursive solutions are often less efficient, in terms of both time
and space, than iterative solutions
• Recursion can simplify the solution of a problem, often resulting
in shorter, more easily understood source code
• Write a function that computes the sum of numbers from 1 to n
int sum (int n)
1. use a loop
2. recursively
i<=n
;
i++)
//with a loop
int sum (int n) {
int s = 0;
for (int i=0;
s+= i;
return s;
}
//recursively
int sum (int n) {
if (n == 1)
return 1;
else
return n + sum(n-1);
}
Example
Example
• Write a function that computes the sum of numbers from 1 to n, using
• Loop
• Recursive function
Deciding whether to use a recursive solution
• When the depth of recursive calls is relatively "shallow“
• Recursive solutions involve function calls that are added to the call stack.
• Shallow recursive call doesn't lead to excessive memory usage or performance issues.
• When the recursive version does about the same amount of work as the nonrecursive
version
• Choosing recursion might lead to more elegant and readable code without
significantly affecting performance.
• When the recursive version is shorter and simpler than the nonrecursive solution
• Improves the readability and maintainability of the code.
Using Input/Output Files
 stream - a sequence of characters
interactive (iostream)
 cin - input stream associated with keyboard.
 cout - output stream associated with display
file (fstream)
 ifstream - defines new input stream (normally associated with a
file).
 The stream extraction operator (>>) may be used to read information
from a file.
 ofstream - defines new output stream (normally associated with a
file).
 The stream insertion operator (<<) may be used to write information
to a file.
 outputFile << “I love C++ programming !”
General File I/O Steps
1. Include the header file fstream in the program.
2. Declare file stream variables.
3. Associate the file stream variables with the
input/output sources.
4. Open the file
5. Use the file stream variables with >>, <<, or
other input/output functions.
6. Close the file.
Ifstreams and ofstreams
File Type Default Open Mode
The file is opened for input only. (Information may be read from the file, but not
written to it.) The file’s contents will be read from its beginning. If the file does not
exist, the open function fails.
ifstream inStream;
instream.open(“infile.dat”);
Int OneNum, anotherNum;
instream >> oneNum>>anotherNum
Instream.close();
The file is opened for output only. (Information may be written to the file, but not
read from the file.) If the file does not exist, it is created. If the file already exists, its
contents are deleted
ofstream outStream;
outstream.open(“outfile.dat”)
outstream<<“oneNum = “<<oneNum <<“ anotherNUm = <<anotherNum;
outstream.close();
ifstream
ofstream
Member Functions
• The eof()member function reports when the end of a file has been encountered.
• The eof() function returns true when there is no more information to be read.
if (inFile.eof())
inFile.close();
• The put Member Function
• outFile.put(ch);
• The getMember Function
• inFile.get(ch);
• The getline Member Function
• dataFile.getline(str, 81, ‘n’);
• str – This is the name of a character array. The information read from the file will be stored here.
• 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80
characters will be read.
• ‘n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading
before it has read the maximum number of characters. (This argument is optional. If it’s left out, ‘n’ is the default.)
File I/O Example: Reading
Read char by char Read a line
#include <iostream>
#include <fstream>
int main()
{//Declare and open a text file
ifstream openFile.open(“data.txt");
char ch;
//do until the end of file
while( ! OpenFile.eof() )
{
OpenFile.get(ch); // get one character
cout << ch; // display the character
}
OpenFile.close(); // close the file
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
int main()
{//Declare and open a text file
ifstream openFile.open("data.txt");
string line;
while(!openFile.eof())
{//fetch line from data.txt and put it in a string
getline(openFile, line);
cout << line;
}
openFile.close(); // close the file
return 0; }
Why do we use Files
• Convenient way to deal with large quantities of data.
• Store data permanently (until the file is deleted).
• Avoid typing data into the program multiple times.
• Share data between programs.
• We need to know:
• how to "connect" file to the program
• how to tell the program to read data
• how to tell the program to write data
• error checking and handling EOF
FUNCTIONS USED IN FILE HANDLING
Function Operation
open() Tocreate a file
close() Toclose an existing file
get() Read a single character from a file
put() write a single character in file.
read() Read data from file
write() Write data into file.

More Related Content

PPT
DS Unit 6.ppt
JITTAYASHWANTHREDDY
 
PPTX
Lecture-11 Friend Functions and inline functions.pptx
rayanbabur
 
PDF
Functions in C++
Pranali Chaudhari
 
PDF
Ch-4-Operator Overloading.pdf
esuEthopi
 
PDF
chapter-8-function-overloading.pdf
study material
 
PDF
4.1 C++ Template for engineering course. Learn easily
kk6369150094
 
PPTX
chapter 5 Templates-Introduction in C++.pptx
RupaRaj6
 
PPT
Bca 2nd sem u-2 classes & objects
Rai University
 
DS Unit 6.ppt
JITTAYASHWANTHREDDY
 
Lecture-11 Friend Functions and inline functions.pptx
rayanbabur
 
Functions in C++
Pranali Chaudhari
 
Ch-4-Operator Overloading.pdf
esuEthopi
 
chapter-8-function-overloading.pdf
study material
 
4.1 C++ Template for engineering course. Learn easily
kk6369150094
 
chapter 5 Templates-Introduction in C++.pptx
RupaRaj6
 
Bca 2nd sem u-2 classes & objects
Rai University
 

Similar to ExamRevision_FinalSession_C++ notes.pptx (20)

PPT
Unit vi(dsc++)
Durga Devi
 
PPT
Mca 2nd sem u-2 classes & objects
Rai University
 
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
PPTX
TEMPLATES IN JAVA
MuskanSony
 
PPTX
Chp 3 C++ for newbies, learn fast and earn fast
nhbinaaa112
 
PPT
Object Oriented Technologies
Umesh Nikam
 
PDF
A COMPLETE FILE FOR C++
M Hussnain Ali
 
PDF
22 scheme OOPs with C++ BCS306B_module1.pdf
sindhus795217
 
PPTX
OOP WITH C++-ppt Slide show unitwise NOTES
RAJESH456811
 
PPTX
functIONS PROGRAMMING CIII II DJDJKASDJKJASD.pptx
nandemprasanna
 
PDF
C++ Object oriented concepts & programming
nirajmandaliya
 
PPTX
Class and object
MushfiqurRahaman7
 
PPTX
object oriented programming language.pptx
syedabbas594247
 
PDF
Class object
Dr. Anand Bihari
 
PPTX
C++ FUNCTIONS-1.pptx
ShashiShash2
 
PPTX
Functions in C++
home
 
PPSX
Object oriented concepts & programming (2620003)
nirajmandaliya
 
PPTX
9781337102087 ppt ch13
Terry Yoast
 
PPTX
class and objects
Payel Guria
 
Unit vi(dsc++)
Durga Devi
 
Mca 2nd sem u-2 classes & objects
Rai University
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
TEMPLATES IN JAVA
MuskanSony
 
Chp 3 C++ for newbies, learn fast and earn fast
nhbinaaa112
 
Object Oriented Technologies
Umesh Nikam
 
A COMPLETE FILE FOR C++
M Hussnain Ali
 
22 scheme OOPs with C++ BCS306B_module1.pdf
sindhus795217
 
OOP WITH C++-ppt Slide show unitwise NOTES
RAJESH456811
 
functIONS PROGRAMMING CIII II DJDJKASDJKJASD.pptx
nandemprasanna
 
C++ Object oriented concepts & programming
nirajmandaliya
 
Class and object
MushfiqurRahaman7
 
object oriented programming language.pptx
syedabbas594247
 
Class object
Dr. Anand Bihari
 
C++ FUNCTIONS-1.pptx
ShashiShash2
 
Functions in C++
home
 
Object oriented concepts & programming (2620003)
nirajmandaliya
 
9781337102087 ppt ch13
Terry Yoast
 
class and objects
Payel Guria
 
Ad

Recently uploaded (20)

PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Software Development Methodologies in 2025
KodekX
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Software Development Company | KodekX
KodekX
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Ad

ExamRevision_FinalSession_C++ notes.pptx

  • 1. 2 Declaration of pointers • int *int_pointer; // pointer to an integer • float *float_pointer; // pointer to a float • double *double_pointer; // pointer to a double • char *str; // pointer to a char or string • int **ptrptr; // pointer to a pointer
  • 2. 3 Using Pointers in C++ 1. We define a pointer variable 2. Assign the address of a variable to a pointer 3. Finally access the value at the address available in the pointer variable • This is done by using the unary operator * that returns the value of the variable located at the address specified by its operand • int var = 20; // actual integer variable • int *ip; // pointer to an integer variable declaration • ip = &var; // store address of var in pointer variable • cout<<ip<<endl; // print the address stored in ip pointer variable • cout <<*ip<<endl; // access the value of the address available in pointer • Dereferencing a pointer gives the value stored at the memory address
  • 6. 7 Pointer Arithmetic • Performing arithmetic operations on pointers • Adding or subtracting an integer value to a pointer moves it to a different memory location • Increment/decrement pointers ( ++ or -- ) • (*ptr)++; • “At the location pointed to by ptr, increment the value by 1.” • Add/subtract an integer to/from a pointer ( + or += , - or -= ) • (*ptr)+=8; • (*ptr)-=5;
  • 7. The this Pointer • The "this" pointer is a reserved pointer in C++ that points to the current object. • It allows objects to access their own members and methods. • In this example, the "this" pointer is used to print the address of the current object.
  • 8. When to Use "this" Pointer • You use the "this" pointer when there is a need to differentiate between class member variables and function parameters with the same name. • "this" pointer is particularly useful in situations where member variables and function parameters share the same name, preventing confusion and enabling access to class members. • this->width = width; assigns the value of the width parameter (the one passed to the setDimensions function) to the class member width. This effectively sets the width of the rectangle. • this->height = height; assigns the value of the height parameter (the one passed to the setDimensions function) to the class member height. This effectively sets the height of the rectangle.
  • 9. Example • The setName method is used to change the student's name. This method demonstrates three different ways to access the name member variable: • name = newName;: Here, we access the member variable directly. • this->name = newName;: We use this-> to access the member variable explicitly. • (*this).name = newName;: We use (*this). to access the member variable explicitly
  • 10. Introduction to Function Templates • So, what exactly are function templates? Function templates are a way of writing functions that can work with multiple data types. • They're like flexible blueprints for functions.
  • 11. Function Overloading Recap • Before we dive into function templates, let's briefly recap function overloading. • Function overloading allows us to have multiple functions with the same name but different parameter lists. • It's an important concept that forms the foundation for function templates.
  • 12. Function Definition • Define function header and function body • Value-returning functions – int, double, char, float return-data-type function-name(parameter list) { constant declarations variable declarations other C++ statements return value }
  • 13. Function Definition (cont.) • Non value-returning functions void function-name(parameter list) { constant declarations variable declarations other C++ statements }
  • 14. Calling a function • A function is called by specifying its name followed by its arguments. • Non-value returning functions: function-name (data passed to function); • Value returning functions: results = function-name (data passed to function); int maxNum = maximum(4,67);
  • 15. Advantages of using functions • Functions can be called multiple times from different parts of the program. • Code can be reused, eliminating the need for redundant code and saving time and effort. • Functions simplify code maintenance by allowing changes in specific functions instead of the entire program
  • 16. Overloading • Providing two or more different definitions of the same function name. • Overloading a function: more than one function in the same class having the same name but differing either in the number of parameters or the types of their parameters. • The easiest way to remember this: the functions’ parameters should qualify any one or more than one of the following conditions:  They should have a different type.  They should have a different number.  They should have a different sequence of parameters. We need to overload the function if we have to perform a single operation with different numbers or types of arguments.
  • 17.  Here’s a small function that you might write to find the maximum of two integers. int maximum(int a, int b) { if (a > b) return a; else return b; } Finding the Maximum of Two Integers
  • 18.  Here’s a small function that you might write to find the maximum of two double numbers. int maximum(double a, double b) { if (a > b) return a; else return b; } Finding the Maximum of Two Doubles
  • 19. Function Template • Function templates are special functions that can operate with generic types. • Function templates allow the logic to be written once and used for all data types – generic function. • This allows us to create a function template whose functionality can be adapted to multiple types or classes without repeating the entire code for each type.
  • 20. Function Template • For example, a function to add two integer and float numbers requires two functions. • One function accepts integer types and the other accepts float types as parameters even though the functionality is the same. • Using a function template, a single function can be used to perform both additions. • It avoids unnecessary repetition of code for doing the same task on various data types • For each call, the compiler generates the complete function, replacing the type parameter with the type or class to which the arguments belong.
  • 21. Function Template Syntax • A function template starts with the keyword template • Followed by template parameter(s) inside <> which is followed by the function definition • T is a template argument that accepts different data types (int, float, etc.) and typename is a keyword • This 'T' can be replaced with any data type when we use the template • When an argument of a data type is passed to functionname(), the compiler generates a new version of functionname() for the given data type
  • 22.  This template function can be used with many data types. template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } A Template Function for Maximum
  • 23.  A template prefix is also needed immediately before the function’s implementation: template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } A Template Function for Maximum
  • 24.  Once a template function is defined, it may be used with any adequate data type in your program... template <class Item> Item maximum(Item a, Item b) { if (a > b) return a; else return b; } Using a Template Function cout << maximum(1,2); cout << maximum(1.3, 0.9); ...
  • 25. Friend Function • We have seen that private members can't be accessed from outside class. Non member function cannot have access to the private data of a class. • Friend function: a function that is not a member of a class, but has access to private members of the class • A friend function can be a stand-alone function or a member function of another class • This function can be defined else where in the program. • It can be declared either in the public or private part of a class without affecting its meaning • It is declared a friend of a class with the friend keyword in the function prototype 11-26
  • 26. Friend Function • Friend functions of an object can "see" inside the object and access private member functions and data. • Syntax: Friend returntype function_name(arguements); Eg: Friend void add();
  • 27. A friend function has certain special characteristics: 1. It is not in the scope of class to which it has been declared as friend 2. Since it is not in the scope of class, it cannot be called using object of that class 3. It can be invoked like a normal function without the help of any object. 4. Unlike member function it can’t access member names directly and has to use an object name and dot membership operator with each member name
  • 28. Access functions • To allow clients to read the value of private data, the class can provide a get function. • To allow clients to modify private data, the class can provide a set function.
  • 29. Implementation of the Friend Function Student &nm Student &age
  • 30. Operator Overloading • If we want to make the operator ‘+’ add two class objects, we have to redefine the meaning of the ‘+’ such that it add two class objects • We achieve this by using the concept of “Operator overloading” • Redefining the meaning of operators does not change their original meaning • It gives them additional meaning along with their existing ones • Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. • Box operator+(const Box&); • Declares the addition operator to add two Box objects and returns the final Box object
  • 31. The syntax for C++ Operator Overloading • To overload an operator, we use a special operator function • The function is mostly defined inside the class or structure whose objects/variables we want the overloaded operator to work with • Here • returnType is the return type of the function • operator is a keyword • symbol is the operator we want to overload like: +, <, -, ++, etc. • arguments is the arguments passed to the function
  • 32. Restrictions on Operator Overloading • C++ operators that can be overloaded • C++ Operators that cannot be overloaded Operators that cannot be overloaded . .* :: ?: sizeof Operators that can be overloaded + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[]
  • 33. Rules of operator overloading • We can overload an operator as its type only i.e., a unary operator cannot be overloaded as a binary operator and vice versa. • We can’t overload operators that are not a part of C++. • At least one operand must be a user-defined class object • We cannot change the operator’s existing functionality. • When unary operators are overloaded through a member function, they do not take any explicit arguments. But when overloaded by a friend function or non-member function, they take one argument. • When binary operators are overloaded through a member function, they take one explicit argument. If overloaded through a friend function or non-member function, they instead take two explicit arguments. • There is a left-hand-side operand and a right-hand-side operand • x ‘operator’ y (x+y or x*y), x is the left-hand-side operand and y is the right-hand-side operand • The whole expression has a value after applying the operator
  • 34. Ways of operator overloading • Operator overloading of member functions. • Operator overloading of non-member or friend functions.
  • 35. Difference between Member and friend function • Friend or non-member function: • More parameters can be passed. • Unary operators take one explicit parameter. • Binary operators take two explicit parameters (need parameters for both operands) • You can make the operator overloading function a friend function if it needs to access the private and protected class members. • If the left operand must be a built-in type or object of a different class, it must be a non- member function
  • 37. Difference between Member and friend function cont.. • Member function: • The number of parameters to be passed is reduced by one, as the calling object is implicitly supplied as an operand. • The leftmost object must be of the same class as the operator • Unary operators take no explicit parameters. • Binary operators take only one explicit parameter. • The operator overloading function may be a member function when the left operand is an object of the Class.
  • 38. Member Function - Example Point result; result.x = this->x + other.x; result.y = this->y + other.y;
  • 39. Overloading Types of Operators • ++, -- operators overloaded differently for prefix vs. postfix notation • Prefix notation • Increment and decrement operators are placed before the operand (++obj, --obj) • Overloaded increment/decrement operator returns the updated object after incrementing or decrementing • It performs the operation first, then returns the modified object • Postfix notation • Increment and decrement operators are placed after the operand (obj++, obj--) • Overloaded increment/decrement operator returns a copy of the original object before incrementing or decrementing • It creates a temporary copy of the object, performs the operation on the original object, then returns the copy • Overloaded relational operators should return a bool value • Overloaded stream operators >>, << must return istream, ostream objects and take istream, ostream objects as parameters 11-40
  • 40. 41 Stream Insertion and Extraction Operators as Global Functions • Overload << operator used where • Left operand of type ostream & • Such as cout object in cout << classObject • Overload >> has left operand of istream & • Left operand of type istream & • Such as cin object in cout >> classObject • Reason:– • These operators are associated with class of right operand
  • 41. What Is Inheritance? • Provides a way to create a new class from an existing class • The new class is a specialized version of the existing class 42
  • 42. The "is a" Relationship • Inheritance establishes an "is a" relationship between classes. – A poodle is a dog – A car is a vehicle – A flower is a plant – A football player is an athlete 43
  • 43. Inheritance • Base class (or parent) – inherited from • Derived class (or child) – inherits from the base class • Notation: class Student // base class { . . . }; class UnderGrad : public student { // derived class . . . }; 44
  • 44. Back to the ‘is a’ Relationship • An object of a derived class 'is a(n)' object of the base class • Example: • an UnderGrad is a Student • a Mammal is an Animal • A derived object has all of the characteristics of the base class 45
  • 45. What Does a Child Have? An object of the derived class has: • all members defined in the child class • these are the members unique to the derived class and not inherited from the parent class. • All members declared in parent class • all the members (both variables and functions) declared in the parent class. This includes public, protected, and private members, but the access level depends on the inheritance type (public, protected, or private). An object of the derived class can use: • All public members defined in the child class • All public members defined in the parent class 46
  • 46. Class Access Specifiers 1) public – object of derived class can be treated as object of base class (not vice-versa) 2) protected – more restrictive than public, but allows derived classes to know details of parents 3) private – prevents objects of derived class from being treated as objects of base class. 47
  • 47. Inheritance vs. Access 48 private: x protected: y public: z private: x protected: y public: z private: x protected: y public: z Base class members x is inaccessible private: y private: z x is inaccessible protected: y protected: z x is inaccessible protected: y public: z How inherited base class members appear in derived class private base class protected base class public base class
  • 48. Inheritance vs. Access 49 private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); class Test : public Grade When Test class inherits from Grade class using public class access, it looks like this: private members: int numQuestions: float pointsEach; int numMissed; public members: Test(int, int); void setScore(float); float getScore(); char getLetter();
  • 49. Inheritance vs. Access 50 private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); When Test class inherits from Grade class using protected class access, it looks like this: private members: int numQuestions: float pointsEach; int numMissed; public members: Test(int, int); protected members: void setScore(float); float getScore(); float getLetter(); class Test : protected Grade
  • 50. Inheritance vs. Access 51 private members: int numQuestions: float pointsEach; int numMissed; void setScore(float); float getScore(); float getLetter(); public members: Test(int, int); private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); When Test class inherits from Grade class using private class access, it looks like this: class Test : private Grade
  • 52. Constructors and Destructors in Base and Derived Classes • Derived classes can have their own constructors and destructors • When an object of a derived class is created, the base class’s constructor is executed first, followed by the derived class’s constructor • When an object of a derived class is destroyed, its destructor is called first, then that of the base class 53
  • 53. Recursion • Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first • Recursion is a technique that solves a problem by solving a smaller problem of the same type • In programming recursion is a method call to the same method. In other words, a recursive method is one that calls itself. • Recursive algorithms are simple to understand and prove correct, easy to implement • But! Recursive calls can result in an infinite loop of calls • Recursion needs a base case in order to stop
  • 54. Content of a Recursive Method • Base case(s). • There is a base case (or cases) that is tested upon entry • Values of the input variables for which we perform no recursive calls are called base cases (there should be at least one base case). • Every possible chain of recursive calls must eventually reach a base case. • Recursive calls. • Calls to the current method. • Each recursive call should be defined so that it makes progress towards a base case.
  • 55. How to write a recursive function? • Determine the size factor • how the problem size is reduced with each recursive call. • Determine the base case(s) • (the one for which you know the answer) • When the base case is reached, the recursion stops. • Determine the general case(s) • (the one where the problem is expressed as a smaller version of itself) • Verify the algorithm • (use the "Three-Question-Method") - next slide
  • 56. Three-Question Verification Method 1. Does the function always reach the base case? • Ensure that the recursion progress leads to the base case to prevent infinite recursion 2. Does the function correctly solve the base case? • Verify that the base case solution is correct. 3. Does the function correctly combine results of recursive calls to solve the general case? • Ensure that the recursive calls and their results are combined accurately to solve the overall problem.
  • 57. Recursion vs. iteration • Iteration can be used in place of recursion • An iterative algorithm uses a looping construct • A recursive algorithm uses a branching structure • Recursive solutions are often less efficient, in terms of both time and space, than iterative solutions • Recursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code
  • 58. • Write a function that computes the sum of numbers from 1 to n int sum (int n) 1. use a loop 2. recursively i<=n ; i++) //with a loop int sum (int n) { int s = 0; for (int i=0; s+= i; return s; } //recursively int sum (int n) { if (n == 1) return 1; else return n + sum(n-1); } Example
  • 59. Example • Write a function that computes the sum of numbers from 1 to n, using • Loop • Recursive function
  • 60. Deciding whether to use a recursive solution • When the depth of recursive calls is relatively "shallow“ • Recursive solutions involve function calls that are added to the call stack. • Shallow recursive call doesn't lead to excessive memory usage or performance issues. • When the recursive version does about the same amount of work as the nonrecursive version • Choosing recursion might lead to more elegant and readable code without significantly affecting performance. • When the recursive version is shorter and simpler than the nonrecursive solution • Improves the readability and maintainability of the code.
  • 61. Using Input/Output Files  stream - a sequence of characters interactive (iostream)  cin - input stream associated with keyboard.  cout - output stream associated with display file (fstream)  ifstream - defines new input stream (normally associated with a file).  The stream extraction operator (>>) may be used to read information from a file.  ofstream - defines new output stream (normally associated with a file).  The stream insertion operator (<<) may be used to write information to a file.  outputFile << “I love C++ programming !”
  • 62. General File I/O Steps 1. Include the header file fstream in the program. 2. Declare file stream variables. 3. Associate the file stream variables with the input/output sources. 4. Open the file 5. Use the file stream variables with >>, <<, or other input/output functions. 6. Close the file.
  • 63. Ifstreams and ofstreams File Type Default Open Mode The file is opened for input only. (Information may be read from the file, but not written to it.) The file’s contents will be read from its beginning. If the file does not exist, the open function fails. ifstream inStream; instream.open(“infile.dat”); Int OneNum, anotherNum; instream >> oneNum>>anotherNum Instream.close(); The file is opened for output only. (Information may be written to the file, but not read from the file.) If the file does not exist, it is created. If the file already exists, its contents are deleted ofstream outStream; outstream.open(“outfile.dat”) outstream<<“oneNum = “<<oneNum <<“ anotherNUm = <<anotherNum; outstream.close(); ifstream ofstream
  • 64. Member Functions • The eof()member function reports when the end of a file has been encountered. • The eof() function returns true when there is no more information to be read. if (inFile.eof()) inFile.close(); • The put Member Function • outFile.put(ch); • The getMember Function • inFile.get(ch); • The getline Member Function • dataFile.getline(str, 81, ‘n’); • str – This is the name of a character array. The information read from the file will be stored here. • 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. • ‘n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left out, ‘n’ is the default.)
  • 65. File I/O Example: Reading Read char by char Read a line #include <iostream> #include <fstream> int main() {//Declare and open a text file ifstream openFile.open(“data.txt"); char ch; //do until the end of file while( ! OpenFile.eof() ) { OpenFile.get(ch); // get one character cout << ch; // display the character } OpenFile.close(); // close the file return 0; } #include <iostream> #include <fstream> #include <string> int main() {//Declare and open a text file ifstream openFile.open("data.txt"); string line; while(!openFile.eof()) {//fetch line from data.txt and put it in a string getline(openFile, line); cout << line; } openFile.close(); // close the file return 0; }
  • 66. Why do we use Files • Convenient way to deal with large quantities of data. • Store data permanently (until the file is deleted). • Avoid typing data into the program multiple times. • Share data between programs. • We need to know: • how to "connect" file to the program • how to tell the program to read data • how to tell the program to write data • error checking and handling EOF
  • 67. FUNCTIONS USED IN FILE HANDLING Function Operation open() Tocreate a file close() Toclose an existing file get() Read a single character from a file put() write a single character in file. read() Read data from file write() Write data into file.