(Combined) Mahbub Sir Lecture

Download as pdf or txt
Download as pdf or txt
You are on page 1of 223

CSE 2131

Lect-01
Basic Program Construction
Functions

Functions are one of the fundamental building blocks of C++. The FIRST
program consists almost entirely of a single function called main(). The
only parts of this program that are not part of the function are the first two
lines—the ones that start with #include and using.

The parentheses following the word main are the distinguishing feature of a
function. Without the parentheses the compiler would think that main refers to a
variable or to some other pro- gram element.
Always Start with main()

When you run a C++ program, the first statement


executed will be at the beginning of a function called
main(). The program may consist of many functions,
classes, and other program elements, but on startup,
control always goes to main(). If there is no function
called main() in your program, an error will be
reported when you run the program.
Output Using cout

cout << “Every age has a language of its own\n”;


in C++ to corre- spond to the standard output stream.
String Constants

The phrase in quotation marks, “Every age has a language of


its own\n”, is an example of a string constant.
Preprocessor Directives
#include <iostream>
It isn’t part of a function body and doesn’t end with a
semicolon, as program statements must. Instead, it
starts with a number sign (#). It’s called a
preprocessor directive.
A part of the compiler called the preprocessor deals
with these directives before it begins the real
compilation process.
The preprocessor directive #include tells the compiler
to insert another file into your source file
Header Files
the preprocessor directive #include tells the compiler
to add the source file IOSTREAM to the FIRST.CPP
source file before compiling. Why do this?
IOSTREAM is an exam- ple of a header file
(sometimes called an include file). It’s concerned with
basic input/output operations, and contains
declarations that are needed by the cout identifier and
the << operator. Without these declarations, the
compiler won’t recognize cout and will think << is
being used incorrectly. There are many such include
files. The newer Standard C++ header files don’t have
a file extension, but some older header files, left over
from the days of the C language, have the extension
.H.
The using Directive
A C++ program can be divided into different namespaces. A
namespace is a part of the pro- gram in which certain names are
recognized; outside of the namespace they’re unknown. The
directive
using namespace std;
says that all the program statements that follow are within the std
namespace. Various program components such as cout are
declared within this namespace. If we didn’t use the using direc-
tive, we would need to add the std name to many program
elements. For example, in the FIRST program we’d need to say
std::cout << “Every age has a language of its own.”;
To avoid adding std:: dozens of times in programs we use the
using directive instead.
#
Defining Integer Variables
include <iostream>
using namespace std;
int main() {
int var1;
int var2;
//define var1
//define var2
var1 = 20; //assign value to var1
var2 = var1 + 10; //assign value to var2
cout << “var1+10 is “; //output text
cout << var2 << endl;
return 0;
}
Character Constants
Input with cin
Type float
Type double and long double
The larger floating point types, double and long
double, are similar to float except that they require
more memory space and provide a wider range of
values and more precision. Type double requires 8
bytes of storage and handles numbers in the range
from 1.7x10–308 to 1.7x10308 with a precision of 15
digits. Type long double is compiler-dependent but is
often the same as double.
Type bool
⚫ #include<iostream>
⚫ using namespace std; b1 is = 0
⚫ int main() b2 is = 1
⚫ {
⚫ int x1 = 10, x2 = 20, m = 2;
⚫ bool b1, b2;
⚫ b1 = x1 == x2; // false
⚫ b2 = x1 < x2; // true
⚫ cout << "b1 is = " << b1 << "\n";
⚫ cout << "b2 is = " << b2 << "\n";

}
Variable Type Summary
unsigned Data Types
By eliminating the sign of the character and integer
types, you can change their range to start at 0 and
include only positive numbers. This allows them to
represent numbers twice as big as the signed type.
Lecture 2
Reminder
⚫ Library file has to discuss later
⚫ Procedural and object oriented programming
have to discuss later
Complex number
#include<iostream>
#include<cmath>
#include<complex>
using namespace std;
int main(){
float x,y;
complex<float>c1,c2,c;
c1=complex<float> (2.0,4.0);
cout<<"Enter the real and imaginary parts of a complex
number\n";
cin>>x>>y;
c2=complex<float>(x,y);
c=c1+c2;
cout<<"Summation of complex number is"<< c;
return 0;}
Output of the above code
Enter the real and imaginary parts of a complex number
24
Summation of complex number is(4,8)
Operation of complex variable
⚫ If we add the following code
float x1=real(c);
float x2=imag(c);
cout<<"The real part of the complex sum is"<<x1<<"\n";
cout<<"The imaginary part of the complex sum is"<<x2<<"\n";
Output
Enter the real and imaginary parts of a complex number 29 8
Summation of complex number is(31,12)
The real part of the complex sum is31
The imaginary part of the complex sum is12
cout<<"Absolute value is:" << abs(c)<<"\n";
cout<<"Phase angle is:" << arg(c) <<"\n";

Output:
Absolute value is:13.9284
Phase angle is:1.20362
cout << "Norm value is:"<< norm(c) <<"\n";
cout << "Complex conguate is:" << conj(c) <<"\n";

Output:
Norm value is:194
Complex conguate is:(5,-13)
cout <<"Square root is: "<< sqrt(c) << "\n";
cout << " 3rd power of complex number is :"<<pow(c,3) <<"\n";

cout << "Exponential of complex number is :" << exp(c) <<"\n";


cout << "Log of complex number is :" << log(c) << "\n";

Output:
Square root is: (3,2)
3rd power of complex number is :(-2035,-828)
Exponential of complex number is :(125.239,-79.6345)
Log of complex number is :(2.56495,1.17601)
Complex variable operation
⚫ Trigonometric and hyperbolic function of
complex variable ---self studys
Logical variable
⚫ Boolean variable studied as bool variable
Relational Operators
In C++ Programming, the values stored in two
variables can be compared using following
operators and relation between them can be
determined.
⚫ Various C++ relational operators available are-
⚫ Operator, Meaning
⚫ > ,Greater than
⚫ >= , Greater than or equal to
⚫ == , Is equal to
⚫ != , Is not equal to
⚫ < , Less than or equal to <=
Now if the result after comparison of two
variables is True, then if statement returns value
1.

And if the result after comparison of two variables


is False, then if statement returns value 0.
#include<iostream>
using namespace std;
int main()
{
int a=10,b=20,c=10;
if(a>b)
cout<<"a is greater"<<endl;
if(a<b)
cout<<"a is smaller"<<endl;
if(a<=c)
cout<<"a is less than/equal to c"<<endl;
if(a>=c)
cout<<"a is less than/equal to c"<<endl;
Return 0;}
a is smaller
a is less than/equal to c
a is greater than/equal to c
Logical Operator
⚫ Logical Operators are used if we want to
compare more than one condition.
⚫ Depending upon the requirement, proper logical
operator is used.
⚫ Following table shows us the different C++
operators available.
⚫ Example
&& AND Operator Binary
|| OR Operator Binary
! NOT Operator Unary
According to names of the Logical Operators, the
condition satisfied in following situation and
expected outputs are given
⚫ Operator Output
⚫ AND Output is 1 only when conditions on
both sides of Operator become True
⚫ OR Output is 0 only when conditions on
both sides of Operator become False
⚫ NOT It gives inverted Output
#include<iostream>
using namespace std;
int main() {
int num1=30;
int num2=40;
if(num1>=40 || num2>=40)
cout<<"OR If Block Gets Executed"<<endl;
if(num1>=20 && num2>=20)
cout<<"AND If Block Gets Executed"<<endl;
if(!(num1>=40))
cout<<"NOT If Block Gets Executed"<<endl;
return 0;}
output
OR If Block Gets Executed
AND If Block Gets Executed
NOT If Block Gets Executed
For loop
#include <iostream>
using namespace std;
int main() {
int j;
for(j=0; j<15; j++)
cout << j * j << “ “; //displaying the square of j
cout << endl;
return 0;
}
Output:
0 1 4 9 16 25 36 49 64 81 100 121 144 169 196
Structure & Function
Lect-03
Structure

A structure is a collection of simple variables.


The variables in a structure can be of different
types: Some can be int, some can be float, and
so on. (This is unlike the array, which we’ll meet
later, in which all the variables must be the same
type.) The data items in a structure are called the
members of the structure.
Structures within structures

struct Room {
struct Distance
{
Distance length;
int feet;
Distance width;
}
float inches;
Room dining;
dining.length.feet = 13;
dining.length.inches = 6.5;
dining.width.feet = 10;
dining.width.inches = 0.0;
Initialize nested structure

Room dining = { {13, 6.5}, {10, 0.0} };


Enumeration

enum days_of_week { Sun, Mon, Tue, Wed, Thu,


Fri, Sat };
int main() {
days_of_week day1, day2;

day1 = Mon;
day2 = Thu;
int diff = day2 - day1;
Example of Enumeration
enum months { Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec };
enum switch { off, on };
enum meridian { am, pm };
enum chess { pawn, knight, bishop, rook, queen,
king };
enum coins { penny, nickel, dime, quarter, half-
dollar, dollar };
Functions
A function groups a number of program
statements into a unit and gives it a name. This
unit can then be invoked from other parts of the
program.
The most important reason to use functions is to
aid in the conceptual organization of a program.
Another reason to use functions (and the reason
they were invented, long ago) is to reduce
program size. Any sequence of instructions that
appears in a program more than once is a
candidate for being made into a function. The
function’s code is stored in only one place in
memory, even though the function is executed
many times in the course of the program.
#include <iostream> void starline()
using namespace std;
void starline();
int main() { {
for(int j=0; j<45;
starline(); j++)
cout << “Data type Range cout << ‘*’;
\n”; cout << endl;
starline(); }
return 0;
}
Eliminating the declaration
#include <iostream>
using namespace std; int main() {
void starline()
starline();
{ cout << “Data type
for(int j=0; j<45; j++) Range \n”;
cout << ‘*’; starline();
cout << endl; return 0;
} }
Passing arguments
#include <iostream>
using namespace std; void starline(char ch, int n)
void starline(char, int);
int main() { {
for(int j=0; j<n; j++)
starline(‘-’,45); cout << ch;
cout << “Data type Range cout << endl;
\n”; }
starline(‘=’, 45);
return 0;
}
Passing variables
#include <iostream>
void starline(char ch, int n)
using namespace std;
void starline(char, int);
{
int main() {
for(int j=0; j<n; j++)
Char chin; int nin
cout << ch;
cin>> chin;
cout << endl;
cin >>nin
}
starline(chin,nin);
return 0;
}
Passing structure argument

#include <iostream>
using namespace std;
struct Distance {
int feet;
float inches;
};
void engldisp( Distance );
int main() {
Distance d1, d2; //define two lengths
cout << “Enter feet: “; cin >> d1.feet;
cout << “Enter inches: “; cin >> d1.inches;
cout << “\nEnter feet: “; cin >> d2.feet;
cout << “Enter inches: “; cin >> d2.inches;
cout << “\nd1 = “;
engldisp(d1);
cout << “\nd2 = “;
engldisp(d2);
cout << endl;
return 0;
}
void engldisp( Distance dd )

{
cout << dd.feet << “\’-” << dd.inches << “\””;
}
Output
Enter feet: 6
Enter inches: 4

Enter feet: 5
Enter inches: 4.25
Functions
Lect-04
Returning Values from Functions
#include <iostream> float lbstokg(float pounds)
using namespace std; {
float lbstokg(float); float kilograms = 0.453592 * pounds;
int main() return kilograms;
{ }
float lbs, kgs;
cout << “\nEnter your
Enter your weight in pounds: 182
weight in pounds: “;
Your weight in kilograms is 82.553741
cin >> lbs;
kgs = lbstokg(lbs);
cout << “Your weight in
kilograms is “ << kgs <<
endl;
return 0;
}
Returning Structure Variables
#include <iostream>
using namespace std;
struct Distance
cout << “Enter feet: “;cin >>d2.feet;
{
cout << “Enter inches: “; cin >>d2.inches;
int feet;
d3 = addengl(d1, d2);
float inches;
cout << endl;
};
engldisp(d1); cout << “ + “;
Distance addengl(Distance,
engldisp(d2); cout << “ = “;
Distance);
engldisp(d3); cout << endl;
void engldisp(Distance);
return 0;
int main()
}
{
Distance d1, d2, d3;
cout << “\nEnter feet: “;cin
>>d1.feet;
cout << “Enter inches: “; cin
>>d1.inches;
void engldisp( Distance dd )
Distance addengl( Distance dd1, Distance
{
dd2 )
cout << dd.feet << “\’-” <<
{
dd.inches << “\””;
Distance dd3;
}
dd3.inches = dd1.inches + dd2.inches;
dd3.feet = 0;
if(dd3.inches >= 12.0) Enter feet: 4
{ Enter inches: 5.5
dd3.inches -= 12.0; Enter feet: 5
dd3.feet++; Enter inches: 6.5
} 4’-5.5” + 5’-6.5” = 10’-0”
dd3.feet += dd1.feet + dd2.feet;
return dd3;
}
#include <iostream>
using namespace std; void intfrac(float n, float&
void intfrac(float, float&, float&); intp, float& fracp)
int main() {
{ long temp =
float number, intpart, fracpart; static_cast<long>(n);
do { //convert to long,
cout << "Enter a real number: "; intp =
//number from user static_cast<float>(temp);
cin >> number; //back to float
intfrac(number, intpart, fracpart); fracp = n - intp;
cout << "Integer part is " << intpart<< ", fraction }
part is " << fracpart << endl; Enter a real number: 99.44
} while( number != 0.0 ); Integer part is 99, fractional
//exit loop on 0.0 part is 0.44
return 0;
}
Different Numbers of Arguments
#include <iostream> void repchar(char ch)
using namespace std; {
void repchar(); for(int j=0; j<45; j++)
void repchar(char); cout << ch;
void repchar(char, int); cout << endl;
}
int main() void repchar(char ch, int n)
{ {
repchar(); for(int j=0; j<n; j++)
repchar(‘=’); cout << ch;
repchar(‘+’, 30); cout << endl;
return 0; }
}

void repchar()
{
Different Kinds of Arguments
#include <iostream> cout << “Enter entire distance in
using namespace std; inches: “; cin >> d2;
struct Distance engldisp(d1);
{ engldisp(d2);
int feet; cout << endl;
float inches; return 0;
}; }
void engldisp( Distance ); void engldisp( Distance dd )
void engldisp( float ); {
int main() cout << dd.feet << “\’-” << dd.inches
{ << “\””;}
Distance d1; void engldisp( float dd )
float d2; {int feet = static_cast<int>(dd / 12);
cout << “\nEnter feet: “; cin >> d1.feet; float inches = dd - feet*12;
cout << “Enter inches: “; cin >> cout << feet << “\’-” << inches <<
d1.inches; “\””;}
Recursion
The existence of functions makes possible a programming technique called
recursion.Recursion involves a function calling itself. This sounds rather
improbable, and indeed a function calling itself is often a bug. However, when
used correctly this technique can be surprisingly powerful.
#include <iostream>
using namespace std; unsigned long factfunc(unsigned long
unsigned long factfunc(unsigned long); n)
int main() {
{ if(n > 1)
int n; return n * factfunc(n-1); //self call
unsigned long fact; else
cout << “Enter an integer: “; return 1;
cin >> n; }
fact = factfunc(n);
cout << “Factorial of “ << n << “ is “ << fact
<< endl;
return 0;
}
Inline Functions: function save memory
We mentioned that functions save memory space because all the calls to the
function cause the same code to be executed; the function body need not be
duplicated in memory. When the compiler sees a function call, it normally
generates a jump to the function. At the end of the function it jumps back to the
instruction following the call
Inline Functions: small function can slow the process
While this sequence of events may save memory space, it takes some extra time.
There must be an instruction for the jump to the function (actually the assembly-
language instruction CALL or something similar), instructions for saving registers,
instructions for pushing arguments onto the stack in the calling program and
removing them from the stack in the function(if there are arguments), instructions
for restoring registers, and an instruction to return to the calling program. The
return value (if any) must also be dealt with. All these instructions slow down the
program.
Inline Functions can save excution time
To save execution time in short functions, you may elect to put the code in the
function body directly inline with the code in the calling program. That is, each time
there’s a function call in the source file, the actual code from the function is
inserted, instead of a jump to the function.
#include <iostream>
using namespace std;
inline float lbstokg(float pounds)
{
return 0.453592 * pounds;
}

int main()
{
float lbs;
cout << “\nEnter your weight in pounds: “;
cin >> lbs;
cout << “Your weight in kilograms is “ << lbstokg(lbs)
<< endl;
return 0;
}
Default Arguments
Surprisingly, a function can be called without specifying all its arguments. This
won’t work on just any function: The function declaration must provide default
values for those arguments that are not specified.
#include <iostream>
using namespace std; void repchar(char ch, int n)
void repchar(char=’*’, int=45); //defaults supplied
int main() {
{ //
repchar(); if necessary
repchar(‘=’); for(int j=0; j<n; j++)
repchar(‘+’, 30); cout << ch;
return 0; cout << endl;
} }
Local Variables
Variables defined within a function body
void somefunc()
are called local variables because they
{
have local scope. However, they are also
int somevar;
sometimes called automatic variables,
float othervar;
because they have the automatic storage
}
class.
A local variable is not created until the function in which it is defined is called.
(More accurately, we can say that variables defined within any block of code are
not created until the block is executed.
The function returns and control is passed back to the calling program, the
variables are destroyed and their values are lost. The name automatic is used
because the variables are automatically created when a function is
called and automatically destroyed when it returns.
The time period between the creation and destruction of a variable is called its
lifetime (or sometimes its duration)
The idea behind limiting the lifetime of variables is to save memory space.
Scope of the variables
A variable’s scope, also called visibility, describes the locations within a program
from which it can be accessed. It can be referred to in statements in some parts of
the program; but in others, attempts to access it lead to an unknown variable error
message. The scope of a variable is that part of the program where the variable is
visible.
void somefunc()
{
int somevar; //local variables
float othervar;
somevar = 10; //ok
othervar = 11; //ok
nextvar = 12; //illegal: not visible in somefunc()
}
void otherfunc()
{
int nextvar; //local variable
somevar = 20; //illegal: not visible in otherfunc()
othervar = 21; //illegal: not visible in otherfunc()
nextvar = 22; //ok
}
Class and object
Lect-5
Class
We’ve learned about structures, which provide a way to
group data elements. We’ve examined functions, which
organize program actions into named entities. In Class, we’ll
put these ideas together to create classes
A Simple Class
#include <iostream> int main()
using namespace std;

{
class smallobj smallobj s1, s2;
{ s1.setdata(1066);
s2.setdata(1776);
private: s1.showdata();
int somedata; s2.showdata();
public: return 0;
void setdata(int d) }
{ somedata = d; } Output:
Data is 1066
void showdata() Data is 1776
{ cout << “Data is “ << somedata << endl;}
private and public
The body of the class contains two unfamiliar keywords: private and public. What
is their purpose?

A key feature of object-oriented programming is data hiding. This term does not
refer to the activities of particularly paranoid programmers; rather it means that
data is concealed within a class so that it cannot be accessed mistakenly by
functions outside the class. The primary mechanism for hiding data is to put it in a
class and make it private. Private data or functions can only be accessed from
within the class. Public data or functions, on the other hand, are accessible from
outside the class.
Constructor
Lect-06
A constructor is a special type of member function that initialises an object
automatically when it is created. Constructor has the same name as that of the class
and it does not have any return type. Also, the constructor is always public.
class temporary
int main()
{
{
private:
Temporary t1;
int x;
... .. ...
float y;
}
public:

// Constructor

temporary(): x(5), y(5.5)

{ }

};
Another way of definition

#include <iostream> int main()


using namespace std; {
// Default constructor
class construct { called automatically
public: // when the object is
int a, b; created
construct c;
// Default Constructor cout << "a: " << c.a <<
construct() endl
{ << "b: " << c.b;
a = 10; return 1;
b = 20; }
Output:
}
}; a: 10
b: 20
Practical Example of constructor and reason of
private data int main()
#include <iostream> {
using namespace std; Counter c1, c2;
class Counter cout << “\nc1=” << c1.get_count(); //display
{ private: cout << “\nc2=” << c2.get_count();
unsigned int count; c1.inc_count();
public: c2.inc_count();
c2.inc_count();
Counter() : count(0)
{ /*empty body*/ } cout << “\nc1=” << c1.get_count();
void inc_count() cout << “\nc2=” << c2.get_count();
{ count++; }
int get_count() { return count; } cout << endl;
}; return 0;
}
Output: Here, private variable “count” is never used main
function and other functions. Variable “count” is
only utilized by Object counter to count how many
c1=0
time the function is called
c2=0
c1=1
c2=2
C++ Destructors

C++ destructor is a special member function that is executed


automatically when an object is destroyed that has been
created by the constructor. C++ destructors are used to de-
allocate the memory that has been allocated for the object by
the constructor.
C++ Destructor Basics

1. Destructors are special member functions of the class required to free the

memory of the object whenever it goes out of scope.

2. Destructors are parameterless functions.

3. Name of the Destructor should be exactly same as that of name of the class.

But preceded by ‘~’ (tilde).

4. Destructors does not have any return type. Not even void.

5. The Destructor of class is automatically called when object goes out of scope.
#include<iostream> int main( )
using namespace std; {
class Marks Marks m1;
{ Marks m2;
public: return 0;
int maths; }
int science;
//constructor Inside Constructor
Marks() { C++ Object created
cout << "Inside Constructor"<<endl; Inside Constructor
cout << "C++ Object created"<<endl; C++ Object created
}
//Destructor Inside Destructor
~Marks() { C++ Object destructed
cout << "Inside Destructor"<<endl; Inside Destructor
cout << "C++ Object destructed"<<endl; C++ Object destructed
}
};
Lecture 7
Object as function arguments
In the following example the following concepts will be illustrated:

constructor overloading

Defining member function outside class

Object as function arguments


#include <iostream>
using namespace std; Multiple
class Distance definitions of
{ Distance function
private: construction is
int feet; float inches; construction
public: overloading
Distance() : feet(0), inches(0.0){}
Distance(int ft, float in) : feet(ft), inches(in) {}
void getdist() //get length from user
{
cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist() //display distance
{ cout << feet << “\’-” << inches << ‘\”’; }
void add_dist( Distance, Distance ); //declaration
};
Member Functions Defined Outside the Class

void Distance::add_dist(Distance d2, Distance


d3)
{
inches = d2.inches +
d3.inches;
feet = 0;
if(inches >= 12.0)
{
inches -= 12.0;
feet++;
}
feet += d2.feet + d3.feet;
}
Objects as Arguments Enter feet: 17
Enter inches: 5.75
int main() dist1 = 17’-5.75”
{ dist2 = 11’-6.25”
Distance dist1, dist3; dist3 = 29’-0”
Distance dist2(11, 6.25);
dist1.getdist();
dist3.add_dist(dist1, dist2);
cout << “\ndist1 = “; dist1.showdist();
cout << “\ndist2 = “; dist2.showdist();
cout << “\ndist3 = “; dist3.showdist();
cout << endl

}
Object parameter initialization
dist3.add_dist(dist1, dist2);

Besides dist3, the object for which it was called, it can also access dist1 and dist2,
because they are supplied as arguments. You might think of dist3 as a sort of
phantom argument; the member function always has access to it, even though it is
not supplied as an argument. That’s what this statement means: “Execute the
add_dist() member function of dist3.” When the variables feet and inches are
referred to within this function, they refer to dist3.feet and dist3.inches.
The default copy constructor
A no-argument constructor can initialize data members to constant values, and a
multi-argument constructor can initialize data members to values passed as
arguments. Let’s mention another way to initialize an object: you can initialize it
with another object of the same type. Surprisingly, you don’t need to create a
special constructor for this; one is already built into all classes. It’s called the
default copy constructor.
int main() Distance dist2(dist1);
{ And
Distance dist1(11, 6.25); Distance dist3 = dist1;
Distance dist2(dist1); Initialize variable dist2 and
Distance dist3 = dist1; dist3 like dist1
cout << “\ndist1 = “; dist1.showdist();
cout << “\ndist2 = “; dist2.showdist();
cout << “\ndist3 = “; dist3.showdist();
cout << endl;
return 0;
}
Returning Object from Functions
#include <iostream> void getdist()
using namespace std; {
class Distance cout << “\nEnter feet: “; cin >> feet;
Distance class cout << “Enter inches: “; cin >> inches;
{ }
private: void showdist()
int feet; //display distance
float inches; { cout << feet << “\’-” << inches << ‘\”’; }
public: Distance add_dist(Distance);
//constructor (no args) };
Distance() : feet(0), inches(0.0)
{}
//constructor (two args)
Distance(int ft, float in) : feet(ft),
inches(in)
{}
Distance Distance::add_dist(Distance d2)
{
Distance temp;
//temporary variable
temp.inches = inches + d2.inches; //add the inches
if(temp.inches >= 12.0)
{
temp.inches -= 12.0;
//by 12.0 and
temp.feet = 1;
}
temp.feet += feet + d2.feet;
//add the feet
return temp;
}
int main()
{
Distance dist1, dist3;
Distance dist2(11, 6.25);

dist1.getdist();
dist3 = dist1.add_dist(dist2);
cout << “\ndist1 = “;
cout << “\ndist2 = “;
cout << “\ndist3 = “;
cout << endl;
return 0;
}
Structure and Class
you can use structures in almost exactly the same way that you use classes. The
only formal difference between class and struct is that in a class the members are
private by default, while in a structure they are public by default.
Classes, Objects and Memory
Lecture 8
Array of Objects
public:
#include <iostream> void getdist()
using namespace std; //get length from user
class Distance {
//English Distance class cout << “\n
{ Enter feet: “; cin >> feet;
private: cout << “
int feet; Enter inches: “; cin >> inches;
float inches; }

void showdist() const


//display distance
{ cout << feet << “\’-” << inches << ‘\”’; }
};
int main()
{ for(int j=0; j<n; j++)
Distance dist[100]; //display all distances
//array of distances {
int n=0; cout << “\nDistance number “ << j+1 << “ is “;
//count the entries dist[j].showdist();
char ans; }
cout << endl;
cout << endl; return 0;
do { }
//get distances from user
cout << “Enter distance number “ <<
n+1;
dist[n++].getdist();
//store distance in array
cout << “Enter another (y/n)?: “;
cin >> ans;
} while( ans != ‘n’ );
Enterdistance number 1
Enter feet: 5
Enter inches: 4
Enter another (y/n)? y
Enter distance number 2
Enter feet: 6
Enter inches: 2.5
Enter another (y/n)? y
Enter distance number 3
Enter feet: 5
Enter inches: 10.75
Enter another (y/n)? n
Distance number 1 is 5’-4”
Distance number 2 is 6’-2.5”
Distance number 3 is 5’-10.75”
Operator Overloading
The rather forbidding term operator overloading refers to giving the normal C++
operators, such as +, *, <=, and +=, additional meanings when they are applied to
user-defined data types. Normally a = b + c; works only with basic types such as
int and float, and attempting to apply it when a, b, and c are objects of a user-
defined class will cause complaints from the compiler. However, using
overloading, you can make this statement legal even when a, b, and c are user-
defined types.
Overloading Unary Operators
int main()
#include using namespace {
std; Counter c1, c2; //define and
initialize
class Counter { cout << “\nc1=” << c1.get_count();
private: //display cout << “\nc2=” <<
unsigned int count; c2.get_count();
public: ++c1;
Counter() : count(0) ++c2;
//constructor { } unsigned int ++c2;
get_count() / { return count; } cout << “\nc1=” << c1.get_count();
void operator ++ () cout << “\nc2=” << c2.get_count()
{ ++count; } << endl;
}; return 0;
}
Output

c1=0
c2=0
c1=1
c2=2
How do we teach a normal C++ operator to act on a
user-defined operand?
The keyword operator is used to overload the ++ operator in this declarator: void
operator ++ () The return type (void in this case) comes first, followed by the
keyword operator, followed by the operator itself (++), and finally the argument list
enclosed in parentheses (which are empty here). This declarator syntax tells the
compiler to call this member function whenever the ++ operator is encountered,
provided the operand (the variable operated on by the ++) is of type Counter.

the only way it can distinguish between overloaded operators is by looking at the
data type of their operands. If the operand is a basic type such as an int, as in
++intvar; then the compiler will use its built-in routine to increment an int. But if the
operand is a Counter variable, the compiler will know to use our user-written
operator++() instead.
Lecture 9
Nameless Temporary Objects
There are more convenient ways to return temporary
objects from functions and overloaded
operators. Let’s examine another approach
#include <iostream>
using namespace std; int main()
class Counter {
{ Counter c1, c2; //c1=0, c2=0
private: cout << “\nc1=” << c1.get_count();
unsigned int count; cout << “\nc2=” << c2.get_count();
public: ++c1; //c1=1
Counter() : count(0) no args c2 = ++c1;
{} cout << “\nc1=” << c1.get_count();
Counter(int c) : count(c) { } cout << “\nc2=” << c2.get_count()
unsigned int get_count() << endl;
{ return count; } return 0;
Counter operator ++ () { }
++count;
return Counter(count);
} In this program a single statement
}; return Counter(count);
Overloading Binary Operators
Binary operators can be overloaded just as easily as unary operators. we showed
how two English Distance objects could be added using a member function
add_dist():

dist3.add_dist(dist1, dist2);

By overloading the + operator we can reduce this dense-looking expression to

dist3 = dist1 + dist2;


#include <iostream>
using namespace std; Distance Distance::operator +
class Distance{ (Distance d2) const
private: {
int feet; int f = feet + d2.feet;
float inches; float i = inches + d2.inches;
public: if(i >= 12.0)
Distance() : feet(0), inches(0.0) { i -= 12.0; f++; } /return
{} Distance(f,i);
Distance(int ft, float in) : feet(ft), inches(in){ } }
void getdist()
{cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist() const
{ cout << feet << “\’-” << inches << ‘\”’; }
Distance operator + ( Distance ) const;
};
int main()
{
Distance dist1, dist3, dist4;dist1.getdist(); Distance
dist2(11, 6.25);
dist3 = dist1 + dist2;
dist4 = dist1 + dist2 + dist3;
cout << “dist1 = “; dist1.showdist(); cout << endl;
cout << “dist2 = “; dist2.showdist(); cout << endl;
cout << “dist3 = “; dist3.showdist(); cout << endl;
cout << “dist4 = “; dist4.showdist(); cout << endl;
return 0;
} Enter feet: 10
Enter inches: 6.5
dist1 = 10’-6.5” ← from user
dist2 = 11’-6.25” ← initialized in program
dist3 = 22’-0.75” ← dist1+dist2
dist4 = 44’-1.5” ← dist1+dist2+dist3
Lecture 10
Concatenating Strings
The + operator cannot be used to concatenate C-strings.
That is, you can’t say
str3 = str1 + str2;
where str1 , str2 , and str3 are C-string variables (arrays
of type char ), as in “cat” plus “bird”
equals “catbird.”
#include <iostream>
using namespace std; String operator + (String ss) const
#include <string.h> //add Strings
//for strcpy(), strcat() {
#include <stdlib.h>//for exit() String temp;
class String
{ if( strlen(str) + strlen(ss.str) < SZ )
private: {
enum { SZ=80 }; strcpy(temp.str, str);
char str[SZ]; strcat(temp.str, ss.str);
public: }
String() else
{ strcpy(str, ""); } { cout << "\nString overflow"; exit(1); }
String( char s[] ) return temp;
{ strcpy(str, s); } //return temp String
void display() const }
{ cout << str; } };
int main()
{ My Friend Happy new year!
String s1 = "\nMy Friend "; My Friend Happy new year!

String s2 = "Happy new year!";


//uses constructor 2
String s3;
//uses constructor 1
s1.display();
s2.display();
s3.display(); //display strings
s3 = s1 + s2;
s3.display();
cout << endl;
return 0;
}
The second constructor sets the String object to a “normal” (that is, a C-
string) string constant.
It uses the strcpy() library function to copy the string constant into the
object’s data. It’s
called with statements like
String s1(“ Hey Friends“);
The alternative format for calling this constructor, which works with any
one-argument
constructor, is
String s1 = “ Hey Friends “;
Remember that using an enum to set the constant value SZ
is a temporary fix. When all compilers
comply with Standard C++ you can change it to
static const int SZ = 80;
Self-Study
Multiple Overloading (pg-334~339)

The Subscript Operator(pg-340~343)

Data Conversion (pg-344~348)


Inheritance
Lect-11
Inheritance is probably the most powerful feature of object-
oriented programming, after classes themselves. Inheritance
is the process of creating new classes, called derived
classes, from existing or base classes. The derived class
inherits all the capabilities of the base class but can add
embellishments and refinements of its own. The base class is
unchanged by this process.
Inheritance is an essential part of OOP. Its big payoff is that it permits code
reusability. Once a base class is written and debugged, it need not be touched
again, but, using inheritance, can nevertheless be adapted to work in different
situations. Reusing existing code saves time and money and increases a program’s
reliability. Inheritance can also help in the original conceptualization of a
programming problem, and in the overall design of the program.
An important result of reusability is the ease of distributing class libraries. A
programmer can use a class created by another person or company, and, without
modifying it, derive other classes from it that are suited to particular situations.
#include <iostream>
using namespace std; class CountDn : public
class Counter Counter
{ {
protected: public:
unsigned int count; Counter operator -- ()
public: { return Counter(--count); }
Counter() : count(0){ } };
Counter(int c) : count(c){ }
unsigned int get_count() const
{ return count; }
Counter operator ++ ()
{ return Counter(++count); }
};
int main() Output:
{
CountDn c1; c1=0
cout << “\nc1=” << c1.get_count(); c1=3
++c1; ++c1; ++c1; c1=1
cout << “\nc1=” << c1.get_count();
--c1; --c1;
cout << “\nc1=” << c1.get_count();
cout << endl;
return 0;
}
The protected Access Specifier
We have increased the functionality of a class without modifying it. Well,
almost without modifying it. Let’s look at the single change we made to the
Counter class.
The data in the classes we’ve looked at so far, including count in the
Counter class in the earlier program, have used the private access specifier.
In the Counter class in COUNTEN , count is given a new specifier: protected
. What does this do?
Let’s first review what we know about the access specifiers private and public . A
member function of a class can always access class members, whether they are
public or private. But an object declared externally can only invoke (using the dot
operator, for example) public members of the class. It’s not allowed to use private
members. For instance, suppose an object objA is an instance of class A , and
function funcA() is a member function of A . Then in main() (or any
other function that is not a member of A ) the statement objA.funcA();
will not be legal unless funcA() is public. The object objA cannot invoke private
members of class A . Private members are, well, private.
This is all we need to know if we don’t use inheritance. With
inheritance, however, there is a whole raft of additional possibilities.
The question that concerns us at the moment is, can member
functions of the derived class access members of the base class? In
other words, can operator--() in CountDn access count in Counter ?
The answer is that member functions can access members of the
base class if the members are public , or if they are protected . They
can’t access private members.

We don’t want to make count public , since that would allow it to be


accessed by any function anywhere in the program and eliminate the
advantages of data hiding. A protected member, on the other hand, can
be accessed by member functions in its own class or—and here’s the
key—in any class derived from its own class. It can’t be accessed from
functions outside these
classes, such as main() .
Access specifiers without inheritance
Derived Class Constructors
#include <iostream> class CountDn : public Counter
using namespace std; {
class Counter public:
{ CountDn() : Counter(){ }
protected: CountDn(int c) : Counter(c){ }
unsigned int count; CountDn operator -- ()
public: { return CountDn(--count); }
Counter() : count(0){ } };
Counter(int c) : count(c){ }
unsigned int get_count()
const
{ return count; }
Counter operator ++ ()
{ return Counter(++count); }
};
int main()
{
CountDn c1;
CountDn c2(100); //class CountDn
cout << “\nc1=” << c1.get_count();
cout << “\nc2=” << c2.get_count();
++c1; ++c1; ++c1;
cout << “\nc1=” << c1.get_count(); --
c2; --c2;
cout << “\nc2=” << c2.get_count();
CountDn c3 = --c2;
cout << “\nc3=” << c3.get_count();
cout << endl;
return 0;
}
Inheritance
Lect-12
Derived class constructor
#include <iostream>
using namespace std; class Child : public Parent1,
class Parent1 { public Parent2
public: {
Parent1() public:
{
cout << "Inside first base class" << // child class's
endl; Constructor
} Child()
}; {
class Parent2 { cout <<
public: "Inside child class" << endl;
Parent2() }
{ };
cout << "Inside second base class"
<< endl;
Inside first base class
//main function
Inside second base class
int main() {
Inside child class
// creating object
of class Child
Child obj1;
return 0;
}
Overriding Member Functions

You can use member functions in a derived class that override—that is, have the
same name as—those in the base class. You might want to do this so that calls in
your program work the same way for objects of both base and derived classes.
#include <iostream> class Stack2 : public Stack
using namespace std; {
#include <process.h> public:
class Stack void push(int var)
{ {
protected: if(top >= MAX-1)
enum { MAX = 3 }; { cout << “\nError: stack is full”; exit(1); }
int st[MAX]; Stack::push(var); //call push() in Stack class
int top; }
public: int pop() //take number off stack
Stack() {
{ top = -1; } if(top < 0) //error if stack empty
void push(int var) { cout << “\nError: stack is empty\n”; exit(1); }
{ st[++top] = var; } return Stack::pop(); //call pop() in Stack class
int pop() }
{ return st[top--]; } };
};
int main() Output:
{ 33
Stack2 s1; 22
s1.push(11); 11
s1.push(22); Error: stack is empty
s1.push(33);

cout << endl <<s1.pop();


cout << endl <<s1.pop();
cout << endl <<s1.pop();
cout << endl <<s1.pop();
cout << endl;
return 0;
}
Public and Private Inheritance
class Stack2 : public Stack
What is the effect of the public keyword in this statement, and what are the
alternatives?
The keyword public specifies that objects of the derived class are able to access
public member functions of the base class. The alternative is the keyword private .
When this keyword is used, objects of the derived class cannot access public
member functions of the base class. Since objects can never access private or
protected members of a class, the result is that no member of the base class is
accessible to objects of the derived class.
class A
{ class C : private A
private: //privately-derived class
int privdataA; {
protected: public:
int protdataA; void funct()
public: {
int pubdataA; int a;
}; a = privdataA; //error: not
class B : public A accessible
{ a = protdataA; //OK
public: a = pubdataA; //OK
void funct() }
{int a; };
a = privdataA; //error: not accessible
a = protdataA; //OK
a = pubdataA;//OK
}};
int main()
{
int a;
B objB;
a= objB.privdataA; //error: not accessible
a= objB.protdataA; //error: not accessible
a= objB.pubdataA; //OK (A public to B)

C objC;
a = objC.privdataA; //error: not accessible
a = objC.protdataA; //error: not accessible
a = objC.pubdataA;
return 0;
}
Multiple Inheritance
#include <iostream> class C: public A, public B {
using namespace std; public:
int c = 20;
class A { C() {
public: cout << "Constructor for
int a = 5; class C" << endl;
A() { cout<<"Class C inherits
cout << "Constructor from class A and class B" <<
for class A" << endl; endl;
} }
}; };
class B {
public:
int b = 10;
B() {
cout << "Constructor
for class B" << endl;
}};
int main() {
C obj; Output:
cout<<"a = "<< obj.a <<endl; Constructor for class A
cout<<"b = "<< obj.b <<endl; Constructor for class B
cout<<"c = "<< obj.c <<endl; Constructor for class C
return 0; Class C inherits from
} class A and class B
a = 5
b = 10
c = 20
Virtual Functions

Virtual means existing in appearance but not in reality. When virtual functions are
used, a program that appears to be calling a function of one class may in reality be
calling a function of a different class.
Normal Member Functions Accessed with Pointers
#include <iostream> int main()
using namespace std; {
class Base Derv1 dv1; //object of derived class 1
{ Derv2 dv2; //object of derived class 2
public: Base* ptr; //pointer to base class
void show(){ cout << “Base\n”; } ptr = &dv1;
}; ptr->show();
class Derv1 : public Base ptr = &dv2;
{ ptr->show();
public: return 0;
void show(){ cout << “Derv1\n”; } }
};
class Derv2 : public Base
{ Output:
Base
public: Base
void show(){ cout << “Derv2\n”; }};
Virtual Member Functions Accessed with Pointers
#include <iostream> int main()
using namespace std; {
class Base Derv1 dv1; //object of derived class 1
{ Derv2 dv2; //object of derived class 2
public: Base* ptr; //pointer to base class
virtual void show(){ cout << “Base\n”; } ptr = &dv1;
}; ptr->show();
class Derv1 : public Base ptr = &dv2;
{ ptr->show();
public: return 0;
void show(){ cout << “Derv1\n”; } }
}; The output of this program is
class Derv2 : public Base Derv1
{ Derv2
public:
void show(){ cout << “Derv2\n”; }};
Polymorphism in C++

The word polymorphism means having many forms. In simple words, we can

define polymorphism as the ability of a message to be displayed in more than one

form.

Real life example of polymorphism, a person at a same time can have different

characteristic. Like a man at a same time is a father, a husband, a employee. So a

same person posses have different behavior in different situations. This is called

polymorphism.
Source: https://www.geeksforgeeks.org/polymorphism-in-c/
Polymorphism is considered as one of the important features of Object

Oriented Programming.

In C++ polymorphism is mainly divided into two types:


● Compile time Polymorphism
● Runtime Polymorphism
Compile time polymorphism: This type of polymorphism is achieved by
function overloading or operator overloading.

● Function Overloading: When there are multiple functions with same


name but different parameters then these functions are said to be
overloaded. Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
Operator Overloading: C++ also provide option to overload operators. For
example, we can make the operator (‘+’) for string class to concatenate two
strings. We know that this is the addition operator whose task is to add to
operands. So a single operator ‘+’ when placed between integer operands ,
adds them and when placed between string operands, concatenates them.
Runtime polymorphism: This type of polymorphism is achieved by Function
Overriding.
● Function overriding on the other hand occurs when a derived class has
a definition for one of the member functions of the base class. That base
function is said to be overridden.
Lecture 13
Templates in C++
Source: http://www.cplusplus.com/doc/oldtutorial/templates/

Function templates

Function templates are special functions that can operate with generic types.
This allows us to create a function template whose functionality can be
adapted to more than one type or class without repeating the entire code for
each type.
In C++ this can be achieved using template parameters. A template parameter
is a special kind of parameter that can be used to pass a type as argument: just
like regular function parameters can be used to pass values to a function,
template parameters allow to pass also types to a function. These function
templates can use these parameters as if they were any other regular type.
The format for declaring function templates with type parameters is:

template <class identifier> function_declaration;


template <typename identifier> function_declaration;

The only difference between both prototypes is the use of either the
keyword class or the keyword typename. Its use is indistinct, since
both expressions have exactly the same meaning and behave exactly
the same way.
For example, to create a template function that returns the
greater one of two objects we could use:

template <class myType>


myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
Conditional ternary operator ( ? )
condition ? result1 : result2

If condition is true, the entire expression


evaluates to result1, and otherwise to result2.

7==5 ? 4 : 3 // evaluates to 3, since 7 is not equal to 5.


7==5+2 ? 4 : 3 // evaluates to 4, since 7 is equal to 5+2.
5>3 ? a : b // evaluates to the value of a, since 5 is greater than 3.
a>b ? a : b // evaluates to whichever is greater, a or b.
To use this function template we use the following format for the
function call:

function_name <type> (parameters);

For example, to call GetMax to compare two integer values of type int
we can write:
int x,y;
GetMax <int> (x,y);
When the compiler encounters this call to a template function, it uses the template to
automatically generate a function replacing each appearance of myType by the type
passed as the actual template parameter (int in this case) and then calls it. This
process is automatically performed by the compiler and is invisible to the
programmer.
// function template int main () {
#include <iostream> int i=5, j=6, k;
using namespace std; long l=10, m=5, n;
k=GetMax<int>(i,j);
template <class T> n=GetMax<long>(l,m);
T GetMax (T a, T b) { cout << k << endl;
T result; cout << n << endl;
result = (a>b)? a : b; return 0;
return (result); }
}
We can also define function templates that accept more than one type
parameter, simply by specifying more template parameters between the angle
brackets. For example:
template <class T, class U>
T GetMin (T a, U b) {
return (a<b?a:b);
}
In this case, our function template GetMin() accepts two parameters of
different types and returns an object of the same type as the first parameter
(T) that is passed. For example, after that declaration we could call GetMin()
with:
int i,j;
long l;
i = GetMin<int,long> (j,l);
Using typename (source:https://www.geeksforgeeks.org/templates-cpp/)
C++ adds two new keywords to support templates: ‘template’ and ‘class’. The second keyword can
always be replaced by keyword ‘typename’.
#include <iostream>
using namespace std;

// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
cout << myMax<char>('g', 'e') << endl; // call myMax for char

return 0;
}
Class templates
We also have the possibility to write class templates, so that a class can have
members that use template parameters as types. For example:

template <class T>


class mypair { mypair<int> myobject (115, 36);
T values [2];
public: mypair<double> myfloats (3.0, 2.18);
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
// class templates template <class T>
#include <iostream> T mypair<T>::getmax ()
using namespace std; {
T retval;
template <class T> retval = a>b? a : b;
class mypair { return retval;
T a, b; }
public:
mypair (T first, T second) int main () {
{a=first; b=second;} mypair <int> myobject (100, 75);
T getmax (); cout << myobject.getmax();
}; return 0;
}
C++ Friend Functions (source:
https://www.tutorialspoint.com/cplusplus/cpp_friend_functions.htm)

A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though
the prototypes for friend functions appear in the class definition, friends are
not member functions.

A friend can be a function, function template, or member function, or a class


or class template, in which case the entire class and all of its members are
friends.
To declare a function as a friend of a class, precede the function
prototype in the class definition with keyword friend as follows −

class Box {
double width;

public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
#include <iostream> // Note: printWidth() is not a member function of any
class.
using namespace std; void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
class Box { directly access any member of this class */
double width; cout << "Width of box : " << box.width <<endl;
}
public:
friend void printWidth( Box box ); // Main function for the program
void setWidth( double wid ); int main() {
}; Box box;

// Member function definition // set box width without member function


void Box::setWidth( double wid ) { box.setWidth(10.0);
width = wid;
} // Use friend function to print the wdith.
printWidth( box );

return 0;
Lecture 14
Vector
(Source:https://www.geeksforgeeks.org/vector-in-cpp-stl/)
Vectors are same as dynamic arrays with the ability to
resize itself automatically when an element is inserted or
deleted, with their storage being handled automatically by
the container. Vector elements are placed in contiguous
storage so that they can be accessed and traversed using
iterators. In vectors, data is inserted at the end. Inserting
at the end takes differential time, as sometimes there may
be a need of extending the array. Removing the last
element takes only constant time because no resizing
happens. Inserting and erasing at the beginning or in the
middle is linear in time.
#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> g1;

for (int i = 1; i <= 5; i++)


g1.push_back(i);

cout << "Output of begin and end: ";


for (auto i = g1.begin(); i != g1.end(); ++i)
cout << *i << " ";
cout << "\nOutput of cbegin and cend: ";
for (auto i = g1.cbegin(); i != g1.cend(); ++i)
cout << *i << " ";

cout << "\nOutput of rbegin and rend: ";


for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << *ir << " ";

cout << "\nOutput of crbegin and crend : ";


for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir)
cout << *ir << " ";

return 0;
}
Output of begin and end: 1 2 3 4 5
Output of cbegin and cend: 1 2 3 4 5
Output of rbegin and rend: 5 4 3 2 1
Output of crbegin and crend : 5 4 3 2 1
begin() – Returns an iterator pointing to the first element in the vector
end() – Returns an iterator pointing to the theoretical element that follows the last
element in the vector
rbegin() – Returns a reverse iterator pointing to the last element in the vector
(reverse beginning). It moves from last to first element
rend() – Returns a reverse iterator pointing to the theoretical element preceding the
first element in the vector (considered as reverse end)
cbegin() – Returns a constant iterator pointing to the first element in the vector.
cend() – Returns a constant iterator pointing to the theoretical element that follows
the last element in the vector.
crbegin() – Returns a constant reverse iterator pointing to the last element in the
vector (reverse beginning). It moves from last to first element
crend() – Returns a constant reverse iterator pointing to the theoretical element
preceding the first element in the vector (considered as reverse end)
Difference between iterator and constant iterator
A const_iterator is an iterator that points to const content. This iterator can be
increased and decreased (unless it is itself also const), just like theiterator
returned by vector::begin, but it cannot be used to modify the contents it points to,
even if the vector object is not itself const.
for (auto i = g1.begin(); i != g1.end(); ++i)
vector<int> g1; {
*i=10- *i;
for (int i = 1; i <= 5; i++) cout << *i << " "; //Possible
}
g1.push_back(i); for (auto i = g1.cbegin(); i != g1.cend(); ++i)
{
*i=10-*i;
cout << *i << " "; //not possiblle
}
auto in C++ loop

we must specify the type of an object when we declare it.


Now, C++11 lets us declare objects without specifying
their types.

auto a = 2; // a is an interger
auto b = 8.7; // b is a double
auto c = a; // c is an integer
Another loop of auto
#include <iostream> Output of begin and end: 1
#include <vector> 2345

using namespace std;

int main()
{
vector<int> g1;

for (int i = 1; i <= 5; i++)


g1.push_back(i);
cout << "Output of begin and end: ";
for (auto i:g1)
cout << i << " ";
return 0;
}
this pointer
#include <iostream>

using namespace std;

class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2

if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1"
<<endl;
}

return 0;
}
C++ Exception Handling

An exception is a problem that arises during the execution of a


program. A C++ exception is a response to an exceptional
circumstance that arises while a program is running, such as an
attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a


program to another. C++ exception handling is built upon three
keywords: try, catch,and throw.
● throw − A program throws an exception when a problem shows

up. This is done using a throw keyword.

● catch − A program catches an exception with an exception

handler at the place in a program where you want to handle the

problem. The catch keyword indicates the catching of an

exception.

● try − A try block identifies a block of code for which particular

exceptions will be activated. It's followed by one or more catch

blocks.
#include <iostream> try {
using namespace std; z = division(x, y);
cout << z << endl;
double division(int a, int b) { } catch (const char*
if( b == 0 ) { msg) {
throw "Division by zero condition!"; cerr << msg << endl;
} }
return (a/b);
} return 0;
}
int main () {
int x = 50;
int y = 0;
double z = 0;
typedef in C++
(https://codescracker.com/cpp/cpp-user-defined-data-types.htm )

C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef doest not actually create a new data class, rather it defines a
new name for an existing type. This can increase the portability of a programas only
the typedef statements would have to be changed.

The syntax of the typedef statement is :


typedef float amount;
amount loan, saving, instalment;
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();

typedef int integer;


integer num1, num2, sum;
cout<<"Enter two number: ";
cin>>num1>>num2;
sum=num1+num2;
cout<<"Sum = "<<sum;

getch();
}
Lecture 15
C++ Pointers

A pointer is a variable whose value is the address of another variable.


Like any variable or constant, you must declare a pointer before you
can work with it. The general form of a pointer variable declaration:

int *ip; // pointer to an integer

double *dp; // pointer to a double

float *fp; // pointer to a float

char *ch // pointer to character


// print the address stored in ip
pointer variable
#include <iostream> cout << "Address stored in ip
variable: ";
using namespace std; cout << ip << endl;
int main () { // access the value at the address
int var = 20; // actual variable available in pointer
declaration. cout << "Value of *ip variable: ";
int *ip; // pointer variable cout << *ip << endl;
ip = &var; // store address of var return 0;
in pointer variable }
cout << "Value of var variable: ";
cout << var << endl;
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
C++ Null Pointers

#include <iostream> Thus, if all unused pointers are given the


null value and you avoid the use of a null
using namespace std; pointer, you can avoid the accidental
int main () { misuse of an uninitialized pointer. Many
int *ptr = NULL; times, uninitialized variables hold some
cout << "The value of ptr is " << ptr ; junk values and it becomes difficult to
debug the program.
return 0;
}
C++ Pointer Arithmetic
#include <iostream> for (int i = 0; i < MAX; i++) {
cout << "Address of var[" << i << "] =
using namespace std; ";
const int MAX = 3; cout << ptr << endl;
int main () { cout << "Value of var[" << i << "] = ";
int var[MAX] = {10, 100, 200}; cout << *ptr << endl;
int *ptr;
// point to the next location
// let us have array address in pointer. ptr++;
ptr = var; }
return 0;
}
Address of var[0] = 0xbfa088b0
Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200
C++ Pointers vs Arrays
for (int i = 0; i < MAX; i++) {
#include <iostream> cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
using namespace std;
const int MAX = 3; cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
int main () {
int var[MAX] = {10, 100, 200}; // point to the next location
int *ptr; ptr++;
}
// let us have array address in
pointer. return 0;
ptr = var; }
Pointers and arrays are strongly related. In fact, pointers and arrays
are interchangeable in many cases. For example, a pointer that
points to the beginning of an array can access that array by using
either pointer arithmetic or array-style indexing.
C++ Array of Pointers

#include <iostream>
for (int i = 0; i < MAX; i++) {
using namespace std; cout << "Value of var["
const int MAX = 3; << i << "] = ";
cout << *ptr[i] << endl;
int main () { }
int var[MAX] = {10, 100, 200};
int *ptr[MAX]; return 0;
}
for (int i = 0; i < MAX; i++) {
ptr[i] = &var[i]; // assign the
address of integer.
}
C++ Pointer to Pointer (Multiple Indirection)

A pointer to a pointer is a form of multiple indirection or a chain of pointers.


Normally, a pointer contains the address of a variable. When we define a pointer
to a pointer, the first pointer contains the address of the second pointer, which
points to the location that contains the actual value as shown below.
// take the value using pptr
#include <iostream> cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" <<
using namespace std; *ptr << endl;
cout << "Value available at **pptr :" <<
int main () { **pptr << endl;
int var;
int *ptr; return 0;
int **pptr; }

var = 3000; Value of var :3000


Value available at *ptr :3000
// take the address of var Value available at **pptr :3000
ptr = &var;

// take the address of ptr using address


of operator &
pptr = &ptr;
Passing Pointers to Functions in C++
avg = getAverage( balance, 5 ) ;
#include <iostream>
using namespace std;
// output the returned value
cout << "Average value is: " << avg << endl;
// function declaration:
double getAverage(int *arr, int
return 0;
size); } double getAverage(int *arr, int size) {
int i, sum = 0;
int main () { double avg;
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, for (i = 0; i < size; ++i) {
50}; sum += arr[i];
double avg; }
avg = double(sum) / size;
// pass pointer to the array as an
argument. return avg;
C++ Files and Streams

C++ provides the following classes to perform output and input of


characters to/from files:

● ofstream: Stream class to write on files


● ifstream: Stream class to read from files
● fstream: Stream class to both read and write from/to files
//basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}

Writing this to a file.


Edit & Run
In order to open a file with a stream object we use its member function open:

open (filename, mode);

Where filename is a string representing the name of the file to be opened, and
mode is an optional parameter with a combination of the following flags:
ll these flags can be combined using the bitwise operator OR (|). For example,
if we want to open the file example.bin in binary mode to add data we could
do it by the following call to member function open:

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);

Where filename is a string representing the name of the file to be


opened, and mode is an optional parameter with a combination of
the following flags:
ios::in Open for input operations.

ios::out Open for output operations.


ios::bin Open in binary mode.
ary

ios::ate Set the initial position at the end of the file.


If this flag is not set, the initial position is the beginning of the
file.

ios::app All output operations are performed at the end of the file,
appending the content to the current content of the file.
ios::tru If the file is opened for output operations and it already
nc existed, its previous content is deleted and replaced by the
new one.
Each of the open member functions of classes ofstream, ifstream and fstream
has a default mode that is used if the file is opened without a second
argument:

class default mode


parameter
ofstream ios::out

ifstream ios::in

fstream ios::in | ios::out


To check if a file stream was successful opening a file, you can do it by calling
to member is_open. This member function returns a bool value of true in the
case that indeed the stream object is associated with an open file, or false
otherwise:

if (myfile.is_open()) { /* ok, proceed with output */ }


File opening check
#include <iostream> This is a line.
#include <fstream> This is another line.
using namespace std;

int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
//reading a text file else cout << "Unable to
#include <iostream> open file";
#include <fstream>
#include <string> return 0;
using namespace std; }

int main () {
string line; This is a line.
ifstream myfile ("example.txt"); This is another line.
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
Checking state flags
The following member functions exist to check for specific states of a stream (all of
them return a bool value):

bad() :Returns true if a reading or writing operation fails. For example, in the case
that we try to write to a file that is not open for writing or if the device where we try
to write has no space left.
fail() :Returns true in the same cases as bad(), but also in the case that a format
error happens, like when an alphabetical character is extracted when we are trying
to read an integer number.
eof() :Returns true if a file open for reading has reached the end.
get and put stream positioning
All i/o streams objects keep internally -at least- one internal position:

ifstream, like istream, keeps an internal get position with the location of the
element to be read in the next input operation.

ofstream, like ostream, keeps an internal put position with the location where
the next element has to be written.

Finally, fstream, keeps both, the get and the put position, like iostream.

These internal stream positions point to the locations within the stream
where the next reading or writing operation is performed. These positions
can be observed and modified using the following member functions:
tellg() and tellp()
These two member functions with no parameters return a value of the
member type streampos, which is a type representing the current get
position (in the case of tellg) or the put position (in the case of tellp).
seekg() and seekp()
These functions allow to change the location of the get and put
positions. Both functions are overloaded with two different prototypes.
The first form is:

seekg ( position );
seekp ( position );

Using this prototype, the stream pointer is changed to the absolute


position position (counting from the beginning of the file). The type for
this parameter is streampos, which is the same type as returned by
functions tellg and tellp.

The other form for these functions is:

seekg ( offset, direction );


seekp ( offset, direction );
Using this prototype, the get or put position is set to an offset value relative to some
specific point determined by the parameter direction. offset is of type streamoff. And
direction is of type seekdir, which is an enumerated type that determines the point
from where offset is counted from, and that can take any of the following values:

ios::beg offset counted from the beginning of the stream

ios::cur offset counted from the current position

ios::end offset counted from the end of the stream


// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;

int main () {
streampos begin,end;
ifstream myfile ("example.bin", ios::binary);
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}

You might also like