0% found this document useful (0 votes)
9 views514 pages

All (OOPS)

The document introduces object-oriented programming (OOP) concepts using C++, comparing it to assembling a computer from components. It outlines the principles of OOP such as encapsulation, inheritance, and polymorphism, and discusses the structure of C++ programs, including basic constructs and input/output operations. Additionally, it highlights the differences between procedural programming in C and object-oriented programming in C++.

Uploaded by

dbirthalbe23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views514 pages

All (OOPS)

The document introduces object-oriented programming (OOP) concepts using C++, comparing it to assembling a computer from components. It outlines the principles of OOP such as encapsulation, inheritance, and polymorphism, and discusses the structure of C++ programs, including basic constructs and input/output operations. Additionally, it highlights the differences between procedural programming in C and object-oriented programming in C++.

Uploaded by

dbirthalbe23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 514

Lecture 1

Introduction
Thinking in Objects
• You can walk into a computer store and, with a
little background and often some help, assemble
an entire PC from various components: a
motherboard, a CPU chip, a video card, a hard
disk, a keyboard, and so on.
• Ideally, when you finish assembling all the various
self-contained units, you have a system in which
all the units work together to create a larger
system with which you can solve the problems
you bought the computer for in the first place.
• Internally, each of those components may be
vastly complicated and engineered by
different companies with different methods of
design. But you don't need to know how the
component works, what every chip on the
board does, or how, when you press the ‘A’
key, an ‘A’ gets sent to your computer. As the
assembler of the overall system, each
component you use is a self-contained unit,
and all you are interested in is how the units
interact with each other.
• Will this video card fit into the slots on the
motherboard, and will this monitor work with
this video card?
• Will each particular component speak the right
commands to the other components it interacts
with so that each part of the computer is
understood by every other part?
• Once you know what the interactions are
between the components and can match the
interactions, putting together the overall system
is easy.
What does this have to do with
programming?
Everything.
Object-oriented programming works in exactly
this same way. Using object-oriented
programming, your overall program is made
up of lots of different self-contained
components (objects), each of which has a
specific role in the program and all of which
can talk to each other in predefined ways.
Problem Statement
Dominos made orders on behalf of registered
customer. An order consists of a number of
items. The order is either pending or serviced.
The following are the set of requirements
regarding placed and serviced orders:
1. An order may be placed by registered
customer.
2. A single customer may place a number of
orders.
3. An order may be deleted or edited before
being serviced.
4. An order must include at least one item (No
null order).
5. The desired quantity of an placed item must
not be null.
6. An order is serviced only after receiving
payment from a customer.
7. The customer can pay by cash or by card.
8. An invoice is made at the time of servicing the
order.
Contents
• Basic Concepts of C++
• Difference between C and C++
• Applications of C++
• How a program is Compiled?
• Simple C++ Program
Basic Concepts of C++
Basic Concepts of C++

Layers of Computer Software


Basic Concepts of C++
Basic Concepts of C++
• Object Oriented Programming is method of programming where a system is
considered as a collection of objects that interact together to accomplish certain
tasks. Objects are entities that encapsulate data and procedures that operate on
the data.
• In OOPS first a concept known as "Object Oriented Analysis (OOA)" is used
to specify the objects in term of real world requirements, their behavior and
interactions required. The next concept would be the "Object Oriented Design
(OOD)" that converts these real-time requirements as a hierarchy of objects in
terms of software development requirement. Finally OOPS is used to
implement the requirements using the C++ programming language.

• The main purpose of object oriented programming is to simplify the design,


programming and most importantly debugging a program. So to modify a
particular data, it is easy to identify which function to use. To add additional
features it is easy to identify where to add functions and its related data.
Basic Concepts of C++

• Object Oriented Programming Language

• Basic Concepts:
• Objects
• Classes
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
Objects
• Basic runtime entity in an object – oriented system.
• Often termed as “instance” of a class.
• Example:
– a person, a place, a bank account etc.
• They can be of any type based on its declaration.
• When program is executed, objects interact by sending messages
at runtime.
• Example 2:
– Two objects namely, “customer”, “account”. Customer object
may send a message to the account object requesting for bank
balance.
Classes
• Class is a collection of objects of similar type.
• Class is a way to bind the data and its associated functions
together.
• Objects are basically variable of the class or an object is an
instance of a class.
• Examples:
– Shape is a class and Rectangle, Square, Triangle are its objects.

Abstraction
• Providing only essential information to the outside world i.e. to
represent the needed information in program without presenting the
details.
• Data abstraction is a programming/ design technique that relies on
the separation of interface and implementation.
• In C++, they provide sufficient public methods to the outside world
to play with the functionality of the object and to manipulate object
data, i.e., state without actually knowing how class has been
implemented internally.

• Eg: While using an object (that is an instance of a class) the


built in data types and the members in the class are ignored.
This is known as data abstraction.
Abstraction
Encapsulation
• All C++ programs are composed of the following two
fundamental elements:
– Program statements (code): This is the part of a program that
performs actions and they are called functions.
– Program data: The data is the information of the program which
affected by the program functions.

• Encapsulation is an Object Oriented Programming concept that


binds together the data and functions that manipulate the data,
and that keeps both safe from outside interference and misuse.

• Data encapsulation led to the important OOP concept of data


hiding.
Encapsulation
• C++ supports the properties of encapsulation and data hiding
through the creation of user-defined types, called classes.
• Eg: a class can contain
– private, protected, public members.
Inheritance
• Inheritance works on the basis of re-usability.

• This provides us an opportunity to reuse the code functionality


and fast implementation time.

• When creating a class, instead of writing completely new data


members and member functions, the programmer can designate
that the new class should inherit the members of an existing
class. This existing class is called the base class, and the new
class is referred to as the derived class.

• The idea of inheritance implements the is a relationship.


Inheritance
Polymorphism
• Poly means many and morphism means changing or alterable.
• The word polymorphism means having many forms.
Polymorphism

• C++ polymorphism means that a call to a member function will


cause a different function to be executed depending on the type
of object that invokes the function.
Dynamic Binding
• Binding refers to the linking of a procedure call to the
code to be executed in response to the call.

• Dynamic binding (late binding) means that the code


associated with a given procedure call is not known
until the time of the call at run-time.

• Associated with polymorphism and inheritance.


Message Passing
• OOPs consists of a set of objects that communicate with each
other.

• This involves following steps:


– Creating classes that define objects and their behavior
– Creating objects from class definitions.
– Establishing communication among objects

• A message for an object is a request for execution of a


procedure, and therefore will invoke a function (procedure)
in the receiving object that generates the desired result.
Message Passing
• Message passing involves specifying the name of the object,
the name of the function (message) and the information to be
sent.
Difference between C and C++
Difference between C and C++
S. No. Procedural Programming (C) Object Oriented Programming (C++)
1 Emphasis is on doing things Emphasis is on data rather than
(algorithms). procedure.
2 Large programs are divided Programs are divided into objects.
into smaller programs in the Functions that operate together are
form of functions. tied together in the data structure.
3 Most of the functions share Data is mostly hidden and cannot be
global data. accessed by external functions.
4 Data move openly around the Objects may communicate with each
system from function to other through functions. New data
function. Functions transform and functions can be easily added
data from one form to another. wherever necessary.
5 Employs top-down approach in Follow bottom-up approach in
program design. program design.
Difference between C and C++

Functioning of Procedural Language Functioning of Object Oriented


Programming Language
Difference between C and C++
• A class is an extension of the idea of structure used in
C.
• A new way of creating and implementing user-
defined data type.
C Structures
• Provide a method for packing together data of different types.
• A convenient tool for handling a group of logically related data
items.
• Eg:
struct student
{
char name[20];
int roll_no;
float total_marks;
} A;
Limitations
• Cannot treat struct data-type like built in data type.
Example:
struct Complex
{
float x;
float y;
} c1, c2,c3;
Complex nos. c1, c2, c3 can be easily assigned values using dot
operator, but we can’t directly add or subtract two complex nos.
i.e.
c3 = c1 + c2; // illegal in C.
• Do not permit data hiding. Structure members are public
members.
C++ Classes
• Attempts to bring user defined types as close as
possible to the built-in data types.

• Also provides facility to hide the data.

• Inheritance is also supported by C++


Applications
Applications of OOPs Languages
• Real-time systems
• Simulation and Modeling
• Object-oriented Databases
• Hypertext and Hypermedia systems
• AI and expert systems
• Neural Networks and parallel programming
• Decision Support and office automation systems
• CIM/CAM/CAD systems
How a Program is Executed?
Flowchart
1. Editor

• C++ program is written in an Editor.


• Saved as a file with extension .cpp.
2. Preprocessor
• Preprocessing performs (usually simple) operations on the
source file(s) prior to compilation.

• Typical preprocessing operations include:


(a) Expanding macros (shorthand notations for longer
constructs). For example, in C,
#define abc(x,y) (3*x+y*(2+x))
In program n = abc(a,b) becomes
n = (3*a+b*(2+a))
• (b) Inserting named files. For example, in C++,
# include <iostream>
is replaced by the contents of the file iostream.h
3. Compiler

• Compiler is a program that can read a program in one


language — the source language — and translate it into
an equivalent program in another language — the target
language or machine language.

• An important role of the compiler is to report any errors


in the source program that it detects during the
translation process.
4. Linker
• A linker combines object code (machine code that
has not yet been linked) produced from compiling
and assembling many source programs, as well as
standard library functions and resources supplied by
the operating system.
5. Loader
• Compilers, assemblers and linkers usually produce code whose
memory references are made relative to an undetermined
starting location that can be anywhere in memory.
(relocatable machine code)

• The loader then puts together all of the executable object files
into memory for execution.

• A loader calculates appropriate absolute addresses for these


memory locations and amends the code to use these addresses.
6. Execute

CPU executes the program one instruction at time.


A Bit more about execution
1. To stop the process
after the preprocessor
step, you can use the -
E option:
g++ -E prog1.cpp
The expanded source
code file will be printed
on standard output (the
screen by default).
2. To stop the process after
the compile step, you can
use the -S option:

g++ -S prog1.cpp

By default, the assembler


code for a source file
named filename.cpp will
be placed in a file
named filename.s.
3. To stop the process after
the assembly step, you
can use -c option:

g++ -c prog1.cpp

By default, the assembler


code for a source file
named filename.cpp will
be placed in a file
named filename.o.
A simple C++ Program
General Structure of C++ Program
“Hello World” in C++
Include standard
Use the standard namespace
iostream classes

using namespace std;


A C++ comment
#include <iostream>
// My first C++ program!
int main(void)
{
cout << "hello world!" << endl;
cout is an return 0;
instance of }
iostream
operator overloading
(two different argument types!)
Thank You
Lecture 2-3
C++ Basic Constructs
Contents
• Structures in C++
• Console Input and Output
• C++ Tokens
• Type Casting
• Control Structures
Structure in C++
#include <iostream>
using namespace std;
struct Person{int age;};
int main(){
Person p1; // No need to write struct Person p1 in C++.
cout << "Enter age: ";cin >> p1.age;
cout <<"Age: " << p1.age << endl;
return 0;
}
Structures in C++ vs in C
1. Functions can be defined inside structure in C++
2. Using struct keyword not required in C++
3. C++ structures can have static members
4. C++ allows data hiding by using access modifiers
#include <iostream>
using namespace std;
struct Person{
int age; //variable
int setAge(int a){age = a;} //function
int display() {cout <<"Age: " << age << endl;} //function
};
int main(){
Person p1;
p1.setAge(20); p1.display();
return 0;
}
Need more knowledge for 3 & 4
1. Functions can be defined inside structure in C++
2. Using struct keyword not required in C++
3. C++ structures can have static members
4. C++ allows data hiding by using access modifiers
Console Input and Output
Console Input / Output
• I/O objects cin, cout
• Defined in the C++ library called <iostream>
• Must have these lines (called pre-processor
directives) near start of file:
– #include <iostream>
using namespace std;
– Tells C++ to use appropriate library so we can
use the I/O objects cin, cout
Console Output

Output using Insertion Operator


**cout: Standard Output Stream
Console Output
• What can be outputted?
– Any data can be outputted to display screen
• Variables
• Constants
• Literals
• Expressions (which can include all of above)
– cout << numberOfGames << " games played.";
2 values are outputted:
"value" of variable numberOfGames,
literal string " games played."
• Cascading: multiple values in one cout
Separating Lines of Output
• New lines in output
– Recall: "\n" is escape sequence for the
char "newline"
• A second method: object endl
• Examples:
cout << "Hello World\n";
• Sends string "Hello World" to display, & escape sequence "\n",
skipping to next line
cout << "Hello World" << endl;
• Same result as above
Input Using cin
• cin for input, cout for output
• Differences:
– ">>" (extraction operator) points opposite
• Think of it as "pointing toward where the data goes"
– Object name "cin" used instead of "cout"
– No literals allowed for cin
• Must input "to a variable"

• cin >> num;


– Waits on-screen for keyboard entry
– Value entered at keyboard is "assigned" to num
Console Input

Input using Extraction Operator


**cin: Standard Input Stream
Prompting for Input: cin and cout
• Always "prompt" user for input
cout << "Enter number of dragons: ";
cin >> numOfDragons;
– Note no "\n" in cout. Prompt "waits" on same
line for keyboard input as follows:

Enter number of dragons: ____

• Underscore above denotes where keyboard entry


is made
Namespaces
• Namespaces defined:
– Collection of name definitions
• For now: interested in namespace "std"
– Has all standard library definitions we need
• Examples:
#include <iostream>
using namespace std;
• Includes entire standard library of name definitions
• #include <iostream>using std::cin;
using std::cout;
• Can specify just the objects we want
C++ Tokens
C++ Tokens
Tokens are the minimal chunk of program that have meaning to the
compiler – the smallest meaningful symbols in the language.
C++ Keywords
C++ Identifiers
• User defined names
• Rules
– An identifier can consist of alphabets, digits and/or
underscores.
– It must not start with a digit.
– C++ is case sensitive i.e., upper case and lower
case letters are considered differently.
– It should not be a reserved word/ declared
keyword.
C++ Identifiers
C++ Variables
– A memory location to store data for a program
– Must declare all data before use in program
Simple Data Types (1 of 2)
Simple Data Types: (2 of 2)
Literal Data
• Literals
– Examples:
• 2 // Literal constant int
• 5.75 // Literal constant double
• ‘Z’ // Literal constant char
• "Hello World" // Literal constant string

• Cannot change values during execution


• Called "literals" because you "literally typed"
them in your program!
Escape Sequences
• "Extend" character set
• Backslash, \ preceding a character
– Instructs compiler: a special "escape character" is
coming
– Following character treated as "escape sequence
char"
Some Escape Sequences (1 of 2)
Some Escape Sequences (2 of 2)
C++ Constants
• Naming your constants
– Literal constants are "OK", but provide little meaning
• Use named constants instead
– Meaningful name to represent data
const int NUMBER_OF_STUDENTS = 24;
• Called a "declared constant" or "named constant"
• Now use it’s name wherever needed in program
Usage of Named Constant
Different Types of Operators
Precedence Examples
• Arithmetic before logical
– x + 1 > 2 || x + 1 < -3 means:
• (x + 1) > 2 || (x + 1) < -3

• Short-circuit evaluation
– (x >= 0) && (y > 1)
– Be careful with increment operators!
• (x > 1) && (y++)

• Integers as boolean values


– All non-zero values → true
– Zero value → false
Type Casting
Assigning Data
• Initializing data in declaration statement
• int myValue = 0;
• Assigning data during execution
– Lvalues (left-side) & Rvalues (right-side)
• Lvalues must be variables
• Rvalues can be any expression
• Example:
distance = rate * time;
Lvalue: "distance"
Rvalue: "rate * time"
Data Assignment Rules
• Compatibility of Data Assignments
– Type mismatches
• General Rule: Cannot place value of one type into variable of
another type
– intVar = 2.99; // 2 is assigned to intVar!
• Only integer part "fits", so that’s all that goes
• Called "implicit" or "automatic type conversion"
– Literals
• 2, 5.75, ‘Z’, "Hello World"
• Considered "constants": can’t change in program
Arithmetic Precision
• Precision of Calculations
– VERY important consideration!
• Expressions in C++ might not evaluate as you’d
"expect"!
– "Highest-order operand" determines type
of arithmetic "precision" performed
– Common pitfall!
Arithmetic Precision Examples
• Examples:
– 17 / 5 evaluates to 3 in C++!
• Both operands are integers
• Integer division is performed!
– 17.0 / 5 equals 3.4 in C++!
• Highest-order operand is "double type"
• Double "precision" division is performed!
– int intVar1 =1, intVar2=2;
intVar1 / intVar2;
• Performs integer division!
• Result: 0!
Individual Arithmetic Precision
• Calculations done "one-by-one"
– 1 / 2 / 3.0 / 4 performs 3 separate divisions.
• First→ 1 / 2 equals 0
• Then→ 0 / 3.0 equals 0.0
• Then→ 0.0 / 4 equals 0.0 !!

• So not necessarily sufficient to change just "one


operand" in a large expression
– Must keep in mind all individual calculations that will be
performed during evaluation!
Type Casting
• Casting for Variables
– Can add ".0" to literals to force precision
arithmetic, but what about variables?
• We can’t use "myInt.0" !
Type Casting
• Two types
– Implicit—also called "Automatic"
• Done FOR you, automatically
17 / 5.5
This expression causes an "implicit type cast" to take place, casting
the 17 → 17.0
– Explicit type conversion
• Programmer specifies conversion with cast operator
(double)17 / 5.5
Same expression as above, using explicit cast
(double) myInt / myDouble
More typical use; cast operator on variable
Control Structures
Control Structures
Branching Mechanisms
• if-else statements
– Choice of two alternate statements based
on condition expression
– Example:
if (hrs > 40)
grossPay = rate*40 + 1.5*rate*(hrs-40);
else
grossPay = rate*hrs;
if-else Statement Syntax
• Formal syntax:
if (<boolean_expression>)
{
<yes_statement>
}
else
{
<no_statement>
}
Common Pitfalls
• Operator "=" vs. operator "=="
• One means "assignment" (=)
• One means "equality" (==)
– VERY different in C++!
– Example:
if (x = 12) Note operator used!
Do_Something
else
Do_Something_Else
Conditional Operator
• Also called "ternary operator"
– Allows embedded conditional in expression
– Essentially "shorthand if-else" operator
– Example:
if (n1 > n2)
max = n1;
else
max = n2;
– Can be written:
max = (n1 > n2) ? n1 : n2;
• "?" and ":" form this "ternary" operator
Nested Statements
• if-else statements contain smaller statements
– Can also contain any statement at all, including another if-
else stmt!
– Example:
if (speed > 55)
if (speed > 80)
cout << "You’re really speeding!";
else
cout << "You’re speeding.";
– Note proper indenting!
Multiway if-else Example
The switch Statement
• A new stmt for controlling multiple branches
• Uses controlling expression which returns bool data
type (true or false)
switch Statement Syntax
The switch Statement in Action
The switch: multiple case labels
• Execution "falls thru" until break
– switch provides a "point of entry"
– Example:
case "A":
case "a":
cout << "Excellent: you got an "A"!\n";
break;
case "B":
case "b":
cout << "Good: you got a "B"!\n";
break;
– Note multiple labels provide same "entry"
Loops
• 3 Types of loops in C++
– while
• Most flexible
• No "restrictions"

– do-while
• Least flexible
• Always executes loop body at least once

– for
• Natural "counting" loop
while Loops Syntax
do-while Loop Syntax
while Loop Example
• Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
– Loop body executes how many times?
do-while Loop Example
count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition

– Loop body executes how many times?


– do-while loops always execute body at least once!
for Loop Syntax

for (Init_Action; Bool_Exp; Update_Action)


Body_Statement
OR
for (Init_Action; Bool_Exp; Update_Action)
{
Body_Statements
}
for Loop Example
• for (count=0;count<3;count++)
{
cout << "Hi "; // Loop Body
}
• How many times does loop body execute?
• Initialization, loop condition and update all "built
into" the for-loop structure!
• A natural "counting" loop
Nested Loops
• Recall: ANY valid C++ statements can be
inside body of loop
• This includes additional loop statements!
– Called "nested loops"
• Requires careful indenting:

for (outer=0; outer<5; outer++)


for (inner=7; inner>2; inner--)
cout << outer << inner;

– Notice no { } since each body is one statement


The break and continue Statements
• Flow of Control
– Recall how loops provide "graceful" and clear flow of
control in and out
– In RARE instances, can alter natural flow
• break;
– Forces loop to exit immediately.
• continue;
– Skips rest of loop body
• These statements violate natural flow
– Only used when absolutely necessary!
Thank You
Week 3
Contents
• Type Casting
• Object Call by value and call by reference
• Nested Member Functions
• Friend Functions
• Inline Functions
• Constructors and Destructors
• Static Class Members
Type Casting
• Two types
– Implicit—also called "Automatic"
• Done for you, automatically
17 / 5.5
This expression causes an "implicit type cast" to take place, casting the 17 → 17.0
– Explicit type conversion
• Programmer specifies conversion with cast operator
(double)17 / 5.5
Same expression as above, using explicit cast
(double) myInt / myDouble
More typical use; cast operator on variable
Program illustrating Typecasting
#include <iostream>
using namespace std;
int main()
Output
{
c=0
int a=2,b=5,c,d; f=0.363636
float e,f=5.0,g,h; c=0 e=0
c=a/f; g=0.4
f=a/5.5; h=0.4
e=a/b;
h= (float)a/(float)b; // C notation
g=float(a)/float(b); //C++ notation
cout<<"c="<<c<<endl<<"f="<<f<<endl
cout<<"e="<<e<<endl<<"g="<<g<<endl<<"h="<<h;
}
Call by value and call by Reference
• Object can be passed as a function argument, like any other
data type to member functions as well as non-member
functions.
• Pass-by-value
• Pass-by-reference
Call by value(object)
• #include <iostream>
• using namespace std;
• class Convert{
• public :
• int i;
• void increment(Convert obj){
• obj.i = obj.i*2;
• cout << "Value of i in member function : " << obj.i;
• } Output
• }; Value of i in member function : 6
• int main(){ Value of i in main : 3
• Convert obj1;
• obj1.i = 3;
• obj1.increment(obj1);
• cout << "\nValue of i in main : " << obj1.i << "\n";
• return 0;
• }
Call by Reference
1. #include <iostream>
2. using namespace std;
3. class Convert
4. { public :
5. int i;
6. void increment(Convert &obj){
7. obj.i = obj.i*2;
8. cout << "Value of i in member function : " <<
Output:
obj.i;
Value of i in member function : 6
9. }
Value of i in main : 6
10. };
11. int main (){
12. Convert obj1;
13. obj1.i=3;
14. obj1.increment(obj1);
15. cout << "\nValue of i in main : " << obj1.i << "\n";
16. return 0;
17. }
Nesting of Member Functions
• A member function calling another member functions is
known as nesting of member functions.
• A member function of a class can be called only by an object of
that class using a dot operator.
• However, there is an exception to this. A member function can
be called by using its name inside another member function of
the same class.
• Private member functions can also be accessed by using
nesting of member functions.
Nesting of Member Functions
1. #include <iostream>
2. using namespace std;
3. class emp{
4. float basic;
5. public:
6. void display(){
7. cout<<basic;
8. }
9. void takeData(){
10. cin>>basic;
11. // A member function of a class can be called by
12. // another member function of the same class
13. // takeData() is calling diaplay()
14. display();
15. }
16.};
17.int main(){
18. emp e1;
19. e1.takeData();
20.}
Exercise (10 minutes)
• Write a program in C++ to create a class Data having member
functions get_data() to input the numbers in an array, largest()
to find the largest number in the array and display () to print
the largest number. Member function largest () and all the data
variables should be private.
1. #include <iostream> 19. int Data::largest(void){
2. using namespace std; 20. int max;
3. class Data{ 21. max = num[0];
4. int num[20]; 22. for(int i=1;i<n;i++){
5. int n; 23. if(max<num[i])
6. int largest(void); 24. max=num[i];
7. public: 25. }
8. void get_data(void); 26. return max;
9. void display(void); 27. }
10. }; 28. void Data::display(void){
11. void Data::get_data(void){ 29. cout<<"The largest
12. cout<<"Enter the total number:"<<largest()<<endl;
numbers(n):"<<endl; 30. }//nesting
13. cin>>n; 31. int main(){
14. cout<<"Enter the number:"<<endl; 32. Data num;
15. for(int i=0;i<n;i++){ 33. num.get_data();
16. cout<<"Enter the 34. num.display();
number"<<i+1<<";"; cin>>num[i]; 35. }
17. }
18. }
Friend Function
• A function that can access the private and protected members of a class
to which it is a friend.
• It is not in the scope of a class to which it is a friend.
• It cannot be called using the object of a class to which it is a friend.
– Invoked like a normal function.
• Has to be declared either in the public or the private section within a
class (to which it is a friend) preceded with a keyword friend.
Contd…
• Defined elsewhere in the program like a normal C++ function.
• Can be a simple function or a member function of some other
class.
• Usually, it has the objects as arguments.
• Best suited in operator overloading.
Example
1. #include <iostream>
2. using namespace std;
3. class myclass{
4. int a, b;
5. public:
6. friend int sum(myclass x);
7. void set_ab(int i, int j);
8. };
9. void myclass::set_ab(int i, int j){
10. a = i;
11. b = j;
12.} Output
13.int sum(myclass x){
14. return x.a + x.b; 7
15.}
16.int main(){
17. myclass n;
18. n.set_ab(3, 4);
19. cout << sum(n);
20. return 0;
14
21.}
Friend of more than one class
1. #include <iostream> 18.void C1::set_status(int state){
2. using namespace std; 19. status = state;
3. const int IDLE = 0;
20.}
4. const int INUSE = 1;
5. class C2; // forward declaration
21.void C2::set_status(int state){
6. class C1 { 22. status = state;
7. int status; 23.}
8. public: 24.int idle(C1 a, C2 b){
9. void set_status(int state); 25. if(a.status || b.status)
10. friend int idle(C1 a, C2 b); 26. return 0;
11.}; 27. else
12.class C2 { 28. return 1;
13. int status;
29.}
14.public:
15. void set_status(int state);
16. friend int idle(C1 a, C2 b);
17.};
Contd…
30.int main(){
31. C1 x; Output
32. C2 y;
Screen can be used.
33. x.set_status(IDLE);
34. y.set_status(IDLE); In use.
35. if(idle(x, y))
36. cout << "Screen can be used.\n";
37. else
38. cout << "In use.\n";
39. x.set_status(INUSE);
40. if(idle(x, y))
41. cout << "Screen can be used.\n";
42. else
43. cout << "In use.\n";
44. return 0;
45.}
Class member as a friend function
1. #include <iostream> 18. void C1::set_status(int state)
2. using namespace std; 19. { status = state; }
3. const int IDLE = 0; 20. void C2::set_status(int state)
4. const int INUSE = 1; 21. { status = state; }
5. class C2; // forward declaration 22. int C1::idle(C2 b)
6. class C1 { 23. { if(status || b.status)
7. int status; 24. return 0;
8. public: 25. else
9. void set_status(int state); 26. return 1; }
10. int idle(C2 b);
11. };
12. class C2 {
13. int status;
14. public:
15. void set_status(int state);
16. friend int C1::idle(C2 b);
17. }; 17
Contd…
Output
27. int main()
28. { C1 x; Screen can be used.
29. C2 y;
In use.
30. x.set_status(IDLE);
31. y.set_status(IDLE);
32. if(x.idle(y))
33. cout << "Screen can be used.\n";
34. else
35. cout << "In use.\n";
36. x.set_status(INUSE);
37. if(x.idle(y))
38. cout << "Screen can be used.\n";
39. else
40. cout << "In use.\n";
41.
5/5/2025 return 0; UTA009 18
Friend Class
• A class can also be made a friend of another class.
class A class B
• Example:
{ ...... { .....
}; friend class A;
..... };

• All the member functions of a friend class A become friend of class B.


• Any member function of class A can access the private data of class B.
• But, member functions of class B cannot access the private data of class
A.

Thapar University UTA007 - Computer Programming I 19


Example
1. #include <iostream>
2. using namespace std;
3. class TwoValues { Output
4. int a, b;
10
5. public:
6. TwoValues(int i, int j) { a = i; b = j;
}
7. friend class Min;
8. }; 1. int main(){
9. class Min { 2. TwoValues ob(10, 20);
10. public: 3. Min m;
11. int min(TwoValues x); 4. cout << m.min(ob);
12.}; 5. return 0;
13.int Min::min(TwoValues x){
6. }
14. return x.a < x.b ? x.a : x.b;
15.}
20
Inline Functions
• In C++, you can create short functions that are not actually
called; rather, their code is expanded in line at the point of
each invocation.
• This process is similar to using a function-like macro.
• To cause a function to be expanded in line rather than called,
precede its definition with the inline keyword.
Example
1. //Code 1. //Compiler Interpretation
2. #include <iostream> 2. //Compiler Interpretation
3. using namespace std; 3. #include <iostream>
4. inline int max(int a, int b){ 4. using namespace std;
5. int main(){
5. return a>b ? a : b;
6. cout << (10>20 ? 10 : 20);
6. }
7. cout << " " << (99>88 ? 99 :88);
7. int main(){
8. return 0;
8. cout << max(10, 20); 9. }
9. cout << " " << max(99, 88);
10. return 0;
11.}
Characteristics of Inline Functions
• Inline functions allow you to create very efficient code.
• Like the register specifier, inline is actually just a request, not a
command, to the compiler.
• If the function definition is too long or complex, the compiler
can choose to ignore it. For example, inline functions may not
work for functions having static variables or recursive
functions.
Inline member functions

1. #include <iostream> 1. // Create another inline function.


2. using namespace std; 2. inline void myclass::show(){
3. class myclass { 3. cout << a << " " << b << "\n";
4. int a, b; 4. }
5. public: 5. int main(){
6. void init(int i, int j); 6. myclass x;
7. void show(); 7. x.init(10, 20);
8. };
8. x.show();
9. // Create an inline function.
9. return 0;
10. inline void myclass::init(int i, int j){
10.}
11. a = i;
12. b = j;
13. }
Defining Inline Functions within a class
• When a function is defined 1. #include <iostream>
inside a class declaration, 2. using namespace std;
3. class myclass {
it is automatically made 4. int a, b;
into an inline function (if 5. public:
possible). 6. // automatic inline
• It is not necessary (but not 7. void init(int i, int j) { a=i; b=j; }
8. void show() { cout << a << " " << b << "\n"; }
an error) to precede its
9. };
declaration with the inline 10. int main(){
keyword. 11. myclass x;
12. x.init(10, 20);
13. x.show();
14. return 0;
15. }
Constructor

▪ A constructor is a special member function of a class whose task is to initialize the


objects of its class.

▪ It has the same name as of that class.

▪ It is invoked on the creation of the object of the associated class.

▪ It can be defined either inside the class or outside the class.


Characteristics of Constructor

▪ It must be declared in the public section of the class.


▪ It does not have any return type (not even void) and therefore
cannot return any value.
▪ It is automatically called when the object is created.
▪ It can also be called explicitly.
▪ It can take parameters.
▪ Constructors can have default arguments.
▪ Constructor can be overloaded.
Characteristics of Constructor (Cont..)

▪ It cannot be inherited (although a derived class constructor can


call a base class constructor).
▪ Constructors cannot be virtual.
▪ We cannot refer to their addresses.
▪ Constructors make implicit call to the operators new and delete
when memory allocation is required.

Note: When a constructor is declared in a class, initialization of class objects


become mandatory.
Declaration of Constructor

▪ Declaration of constructor

//class with a constructor


class classname
{
private:
// variable and function declarations;
public:
// variable and function declarations;
classname(); //constructor (having same name as the class)
};
Example of Constructor
#include<iostream>
int main()
using namespace std; {
class example example e1; //implicit call
{ example e2=example(); //explicit call
private: e1.display();
int a; e2.display();
return 0;
public:
}
example(); //constructor declared
void display( );
}; When a class contains a constructor, it is
example:: example() //constructor defined guaranteed that an object of that class (when
{ created) will be initialized automatically.
a=5;
Not only creates the object e1 of type
} example but also initializes its data member a
void example::display() to 5.
{
cout<<a;
}
Types of Constructor

▪ Default Constructor

▪ Parameterized Constructor

▪ Copy Constructor (will be covered later)


Default Constructor

▪ A constructor that accepts no parameters is called default constructor.

▪ The default constructor for class example is example::example( )


Parameterized Constructors

▪ Sometimes, it may be necessary to initialize the various data elements of different


objects with different values when they are created.

▪ This is achieved by passing arguments to the constructor function when the objects
are created.

▪ The constructors that can take arguments are called parameterized constructors.
Example of Parameterized Constructor

1. class example{
2. private:
3. int a;
4. public: When a constructor is paramete
5. example(int); //Parameterized Constructor must pass the initial values as arg
6. void display( ); the constructor function when an
declared.
7. };
8. example::example(int x){
9. a = x; Two ways Calling:
10.} • 1. Explicit
11.void example::display(){ • example e1 = exam
12. cout<<a<<"\n"; • 2. Implicit
13.} • example e1(5);
• //Shorthand metho
Example 2
1. #include <iostream>
2. using namespace std; 14.int main(){
3. class myclass { 15. myclass ob(3, 5);
4. int a, b; 16. //You can also pass
5. public: arguments as
6. myclass(int i, int j){ 17. // myclass ob=myclass
ob(3, 5);
7. a=i;
18. ob.show();
8. b=j;
19. return 0;
9. }
20.}
10.void show() {
11. cout << a << " " << b;
12. }
13.};
Constructors with Default Arguments

It is possible to define constructors with default arguments.

▪ Consider example (int a, int b= 0);


▪ The default value of the argument b is zero.
example e1(5);
assigns the value 5 to the variable a and 0 to b.
example e1(5, 3);
assigns the value 5 to the variable a and 3 to b.
Constructors with Default Arguments
(Cont..)
▪ example::example() //Default Constructor
▪ example::example(int a=0); //Default Argument Constructor

➢ The default argument constructor can be called with either one argument or no
arguments.

➢ When called with no arguments, it becomes a default constructor.


Constructors with One Parameter: A Special Case
• #include <iostream>
• using namespace std;
• class X {
• int a;
• public:
• X(int j) {
• a = j;
• }
• int geta() {
• return a;
• }
• };
• int main()
• {
• X ob = 99; // passes 99 to j
• cout << ob.geta(); // outputs 99
• return 0;
• }
Dynamic Constructor

▪ The constructor can also be used to allocate memory while creating objects.

▪ This enables the system to allocate the right amount of memory for each object when
the objects are not of the same size.

▪ Allocation of memory to objects at time of their construction is known as dynamic


construction of objects.

▪ The memory is allocated with the help of new operator.


Example 1
1. #include<iostream>
2. using namespace std;
18.void test::display(){
3. class test{ 19. cout<<"The value of object's pointer
4. int *ptr; is:"<<*ptr<<endl;
5. public: 20.}
21.int main(){
6. test(); 22. test obj;
7. test(int); 23. test obj1(40);
8. void display(); 24. obj.display();
25. obj1.display();
9. }; 26. return 0;
10.test::test(){ 27.}
11. ptr=new int;
12. *ptr=100;
13.}
14.test::test(int t){
OUTPUT:
15. ptr=new int; The value of object's pointer is:100
16. *ptr=t; The value of object's pointer is:40
17.}
Example 2
1. class example{
18.void example::display(){
2. char *name; 19. cout<<name<<endl;
3. int length; 20.}
21.int main(){
4. public:
22. char *a= "Welcome to";
5. example(); 23. example e1(a), e2("C++"), e3("World");
6. example(char *); 24. e1.display();
25. e2.display();
7. void display();
26. e3.display();
8. }; 27. return 0;
9. example::example(){ 28.}
10. length = 0;
11. name = new char[length+1];
12.} OUTPUT:
13.example::example(char *e){ Welcome to
14. length = strlen(e); C++
World
15. name = new char[ length+1];
16. strcpy( name,e);
17.}
Destructors
▪ A destructor is a special member
function of class which is used to
destroy the objects that have been
created by a constructor.

class A
▪ The destructor is called {
automatically by the compiler when public:
the object goes out of scope. ~A(); //Destructor declaration
};

▪ Like a constructor, the destructor is a


member function whose name is the
same as class name but is preceded
by a tilde ~ sign.
Destructors (Cont..)

▪ Destructor never takes any argument.

▪ Destructors does not return any value.

▪ Destructor cannot be overloaded.

▪ Whenever new is used to allocate memory in the constructors,


delete should be used to free that memory.

Note: Objects are destroyed in reverse order of their creation.


Example
1. #include<iostream>
2. using namespace std;
3. class ABC{
4. int a; 16.ABC::~ABC(){ //Definition of Destructor
17. cout<<"\nObject is destroyed";
5. public: 18.}
6. ABC(int); //Constructor 19.int main(){
7. void display(); 20. ABC obj1(10);
21. obj1.display();
8. ~ABC(); //Destructor 22. return 0;
9. }; 23.}
10.ABC::ABC(int x){
11. a=x;
12.} Destructor is
13.void ABC::display(){ OUTPUT: automatically called
a=10 by the compiler once
14. cout<<"a="<<a; the object goes out
Object is destroyed of scope.
15.}
When Constructors and Destructors Are Executed
• Global objects have their constructors execute
before main( ) begins execution.
• Global constructors are executed in order of
their declaration, within the same file.
• You cannot know the order of execution of
global constructors spread among several files.
• Global destructors execute in reverse order after
main( ) has terminated.
Example
1. #include<iostream> 16. int main(){
2. using namespace std; 17. myclass local_ob1(3);
3. class myclass { 18. cout << "This will not be first line
displayed.\n";
4. public:
19. myclass local_ob2(4);
5. int who;
20. return 0;
6. myclass(int id);
21. }
7. ~myclass();
8. } glob_ob1(1), glob_ob2(2); Output
9. myclass::myclass(int id){ Initializing 1
10. cout << "Initializing " << id << Initializing 2
"\n"; Initializing 3
11. who = id; This will not be first line displayed.
12. } Initializing 4
13. myclass::~myclass(){ Destructing 4
14. cout << "Destructing " << who << Destructing 3
"\n";
15. } Destructing 2
Destructing 1
Static Class Members
• Static Data Members
• Static Member functions
Static Data Member
• Single copy exists; shared by all the objects.
• Also known as class variables.
• Exists and initialized to zero before any object is
created.
• Within a class, they are declared not defined.
• Public static data member can be accessed directly by
using scope resolution operator.
• Requires a global definition outside the class.
– Re-declaration using scope resolution operator.
48
Example 1
1. #include <iostream> shared Common to all the objects
2. using namespace std;
a set() show()
3. class shared {
4. static int a;
5. int b; Object 1 Object 2 Object O
6. public: b b … b
7. void set(int i, int j) {a=i; b=j;}
8. void show();
9. } ;
10.int shared::a; // define a
11.void shared::show(){
12. cout << "This is static a: " << a;
13. cout << "\nThis is non-static b: " << b;
14. cout << "\n";
15.}
Example 1
Output
int main(){
shared x, y; This is static a: 1
x.set(1, 1); // set a to 1 This is non-static b: 1
x.show();
y.set(2, 2); // change a to 2 This is static a: 2
y.show(); This is non-static b: 2
x.show();
This is static a: 2
return 0;
} This is non-static b: 1

Thapar University 50
Example 2
1. #include <iostream> 7. int main(){
2. using namespace std; 8. // initialize a before
3. class shared { creating any objects
4. public: 9. shared::a = 99;//public
5. static int a; 10. cout << "This is initial
6. } ; value of a: " << shared::a;
11. cout << "\n";
12. shared x;
13. cout << "This is x.a: " <<
x.a;
14. return 0;
15.}
Uses
• Provide access control of shared resource used by all the
objects of a class, e.g. writing a file.

• To keep track of the number of objects of a particular class


type.

• Note:

Virtually eliminates any need for global variables.


Thapar University 52
Static Member Functions
• Can access only other static members of the class.
• Do not have a this pointer.
• They cannot be declared as const or volatile.
• They may not be virtual.
• There cannot be static and non-static version of the same function.
• Can be called using
– An object.
– Class name and scope resolution operator.
Thapar University UTA009 53
Example
• Objective: Write a program to provide access
control to some shared resource.
Example:
Create several objects, each of which wants to print a file on a
specific printer. Clearly, only one object can be allowed to print
a file at a time. In this case, declare a static variable that
indicates when the printer is in use and when it is free. Each
object then interrogates this variable to get the printer.

54
Contd…
1. #include<iostream> 18.int shared :: resource;
2. using namespace std; 19.int main(){
3. class shared{ 20. shared o1, o2;
4. static int resource; 21. if(o1.getResource())
22. cout << "\no1 has resource.";
5. public:
23. if(!shared :: getResource())
6. static int getResource(){ 24. cout << "\no2 access denied.";
7. if(resource) 25. o1.freeResource();
8. return 0; 26. if(shared :: getResource())
9. else{ 27. cout << "\no2 has resource.";
10. resource = 1; 28. return 0;
11. return 1; 29.}
12. }
13. }
14. void freeResource(){
15. resource = 0;
16. }
17. };
55
Uses

• Very limited application.

• Pre-initialize private static data members of a class before any


object is actually created.

56
Example
1. #include <iostream> 13. int static_type::i; // define i
2. using namespace std; 14. int main(){
3. class static_type { 15. // init static data before object
4. static int i; creation
5. public: 16. static_type::init(100);
6. static void init(int x) { 17. static_type x;
7. i = x; 18. x.show(); // displays 100
8. } 19. return 0;
9. void show() { 20. }
10. cout << i;
11. }
12. };

57
Thank You!
Lecture 4-7
Classes and Objects
Contents

• Introduction to Classes and Objects


• Class declaration
• Creating Objects
• Accessing Object Members
• Defining Member Functions
• Nesting of Member Function
• Access Specifiers: Public , Private
• Scope Resolution Operator
• Nested Classes
Classes

• Different from structures


– Adds member functions
– Not just member data

• Integral to object-oriented programming


– Focus on objects
• Object: Contains data and operations
• In C++, variables of class type are objects
Specifying a Class

• A class is a way to bind the data and its associated


functions together.
• A class specification has 2 parts:
– Class declaration
– Class function definitions

• Class declaration: describes type and scope of its members.


• Class function definitions: describes how the class functions
are implemented.
General form of Class declaration
Data Hiding
Difference between Structure and Class

• By default, members of class are private, while, by


default, members of structure are public.

• Encapsulation

• The keywords public and private are known as


visibility labels.
A Simple Class Example
class item
{
int number;
float cost;
public :
void getdata(int a, float b);
void putdata (void);
};
Class Representation

Creating Objects:
item x;

Accessing Class Members:


Object_name.function-name (actual-arguments);
x.getdata(100, 75.5); x.putdata( );
Creating Objects

• Objects can also be created as follows:


Memory Allocation for Objects

• Memory space for objects is allocated when they are


declared and not when the class is specified :
partially true.
• Since all the objects belonging to that class use the
same member functions, no separate space is
allocated for member functions when the objects are
created.
• Only space for member variables is allocated
separately for each object. Because, member
variables will hold different data values for different
objects.
Example
Defining Member Functions
• Outside the class definition • Inside the class definition
When function is defined outside class, it When function is defined inside class, it
requires a prototype declaration in the class. does not require a prototype declaration in
the class.
Inline Functions
• We can define a member function outside the class definition
and still make it inline by using the qualifier inline in the
header line of the function definition.
Nesting of Member Functions

• An object of a class using dot operator generally calls a


member function of the class.

• However, a member function may also be called by using its


name inside another member function of the same class.

• This is known as “Nesting of Member Functions”


Nesting of Member Functions
Data Hiding Revisited
Access Specifiers in C++

3 types of access modifiers available in C++:

• Public

• Private (by default)

• Protected
Access Specifier: Public

• Public members are accessible outside the class.

• Public members are accessible to both member Functions and


non-member Functions.

• Objects can access the members directly using dot operator.


E.g.
– object name.public data member
– object name.public member function
Access Specifier: Public
Access Specifier: Private

• Private Members can only be accessed by the member


functions of that class.

• They cannot be accessed by any non member functions (data is


hidden from outside world).

• Object of a class cannot access private members using dot


operators.

• All data at the beginning of a class is by default private, until


any specifier is mentioned.
Access Specifier: Private
Private Member Functions
Private Member Functions
Scope Resolution Operator

1. Member functions defined outside class


• Using Binary scope resolution operator (::)
• “Ties” member name to class name
• Uniquely identify functions of particular class
• Different classes can have member functions with
same name
• Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){

}
Access Specifiers in C++
class Circle{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r){
radius = r;
}
double Circle::getArea(){
return radius * radius * (22.0/7);
}
double Circle:: getCircumference(){
return 2 * radius * (22.0/7);
}
Scope Resolution Operator
2. To access a global variable when there is a local variable
with same name
#include<iostream>
using namespace std;

int x; // Global x

int main() {
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Scope Resolution Operator
3. To access a class’s static variables
class Test {
static int x;
public:
static int y;
void func(int x) { // We can access class's static variable even if there is a local variable
cout << "Value of static x is " << Test::x;
cout << "\nValue of local x is " << x;
}
};
int Test::x = 1; // In C++, static members must be explicitly defined like this
int Test::y = 2;
int main() {
Test obj;
int x = 3 ;
obj.func(x);
cout << "\nTest::y = " << Test::y;
return 0;
}
Scope Resolution Operator

4. In case of multiple Inheritance

If same variable name exists in two ancestor classes, we can


use scope resolution operator to distinguish.

Detail would be discussed in inheritance………………


Scope Resolution Operator
5. Including In-built libraries.
Scope Resolution Operator
5. Including In-built libraries.

31 // prompt for and input course name


32 cout << "Please enter the course name:" << endl;
33 getline( cin, nameOfCourse ); // read a course name with blanks
34 cout << endl; // output a blank line
35
36 // call myGradeBook's displayMessage function
37 // and pass nameOfCourse as an argument
38 myGradeBook.displayMessage( nameOfCourse );
39 return 0; // indicate successful termination
40 } // end main

Please enter the course name:


CS101 Introduction to C++ Programming

Welcome to the grade book for


CS101 Introduction to C++ Programming!
Nested Classes
• A class is declared within another class.

• The outer class is called enclosing class and inner


class is called the nested class.

• A nested class is a member and as such has the


same access rights as any other member.

• The members of an enclosing class have no


special access to members of a nested class; the
usual access rules shall be obeyed.
Nested Classes Example
#include<iostream>
using namespace std;
class Enclosing /* start of Enclosing class declaration */
{
int x;
class Nested
{ /* start of Nested class declaration */
int y;
void NestedFun(Enclosing e)
{
cout<<e.x; // works fine: nested class can access
// private members of Enclosing class
}
}; // declaration Nested class ends here
}; // declaration Enclosing class ends here
int main(){}
Nested Classes Example
#include<iostream>
using namespace std;
class Enclosing /* start of Enclosing class declaration */
{
int x;
class Nested
{ /* start of Nested class declaration */
int y;
}; // declaration Nested class ends here
void EnclosingFun(Nested n)
{
cout<<n.y; // Compiler Error: y is private in Nested
}
}; // declaration Enclosing class ends here
int main(){}
Thank You
Slide Set 5
• Arrays within a class
• Array of objects
• Object as function arguments
• Returning objects from function
• Dynamic Memory Allocation
• Reference Variables
Arrays within a class
• Arrays can be used as class member variables.

• a is an integer array.
class array • It is declared as a private data
{ int a[10]; member of the class array.
public: • Can be used in class member
functions.
void setVal();
void sort();
void display();
}; 2
Example
1. #include<iostream>
2. using namespace std;
3. class array
4. { int a[10];
5. public:
6. void setVal()
7. { for (int i = 0; i < 10; i++)
8. cin >> a[i]; }
9. void sort()
10. { for (int i = 0; i < 9; i++)
11. for (int j = 0; j < 10 - i - 1; j++)
12. { if (a[j] > a[j + 1])
13. { a[j] = a[j] + a[j + 1];
14. a[j + 1] = a[j] - a[j + 1];
15. a[j] = a[j] - a[j + 1]; } } }
3
Contd…

16. void display() 21. int main()


17. { for (int i = 0; i < 10; i++) 22. {
18. cout << a[i] << '\t';
23. array Arr;
19. }
20. }; 24. Arr.setVal();
25. Arr.sort();
26. cout << "Sorted sequence
is:\n";
Output: 27. Arr.display();
10 9 8 7 6 5 4 3 2 1
28. }
Sorted sequence is:
1 2 3 4 5 6
7 8 9 10
4
Array of objects
•Means array of variables of type class.
•The syntax for declaring and using an object array is exactly the same as
it is for any other type of array.
•Use usual array-accessing methods to access individual elements, and
then the dot member operator to access the member functions.
•An array of objects is stored inside the memory in the same way as a
multi-dimensional array.

5
Contd…

class emp • emp manager[3];


{ char name[10]; // Array of manager
int age; • emp worker[10];
public: // Array of worker
void getData(); Accessing member functions.
void putData(); • manager[i].getData();
}; • manager[i].putData();

6
Contd…
• An array of objects is stored similar to multi-dimensional array.
emp manager[3];

name
manager[0]
age
name
manager[1]
age
name
manager[2]
age
7
Example
1. #include<iostream>
2. using namespace std;
3. class emp
4. { char name[10];
5. int age;
6. public:
7. void getData();
8. void putData();
9. };
10. void emp :: getData()
11. { cout << "Enter Name: "; cin >> name;
12. cout << "Enter Age: "; cin >> age; }
13. void emp :: putData()
14. { cout << "\tName: " << name << "\tAge: " << age << endl; }
8
Contd…
15. int main()
16. { emp manager[3];
17. for (int i = 0; i < 3; i++)
18. { cout << "\nEnter details of manager " << i + 1 << endl;
19. manager[i].getData();
20. }
21. for (int i = 0; i < 3; i++)
22. { cout << "\nManager " << i + 1;
23. manager[i].putData();
24. }
25. return 0;
26. }
9
Output
Enter details of manager 1
Enter Name: Arun
Enter Age: 50

Enter details of manager 2


Enter Name: Amita
Enter Age: 35

Enter details of manager 3


Enter Name: Yashika
Enter Age: 45

Manager 1 Name: Arun Age: 50

Manager 2 Name: Amita Age: 35

Manager 3 Name: Yashika Age: 45

10
Objects as function arguments
• Object can be passed as a function argument, like any other data
type to member functions as well as non-member functions.
• Pass-by-value
• Pass-by-reference

11
Example 1
1. #include <iostream> Output:
2. using namespace std;
3. class Convert Value of i in member function : 6
4. { public : Value of i in main : 3
5. int i;
6. void increment(Convert obj)
7. { obj.i=obj.i*2;
8. cout << "Value of i in member function : " << obj.i;
9. }
10. };
11. int main ()
12. { Convert obj1;
13. obj1.i=3; obj1.increment(obj1);
14. cout << "\nValue of i in main : " << obj1.i << "\n";
15. return 0; } 12
Example 2
#include <iostream> int main()
using namespace std; {
class myclass { myclass o(1);
int i; f(o);
public: cout << "This is i in main: ";
myclass(int n); cout << o.get_i() << "\n";
~myclass(); return 0;
void set_i(int n) { i=n; } }
int get_i() { return i; } void f(myclass ob)
}; {
myclass::myclass(int n) ob.set_i(2);
{ cout << "This is local i: " << ob.get_i();
i = n; cout << "\n";
cout << "Constructing " << i << "\n"; } Output
} Constructing 1
myclass::~myclass() This is local i: 2
{ Destroying 2
cout << "Destroying " << i << "\n"; This is i in main: 1
} Destroying 1
void f(myclass ob);
Example 3 (Pass-by-reference)
1. #include <iostream> Output:
2. using namespace std;
3. class Convert Value of i in member function : 6
4. { public : Value of i in main : 6
5. int i;
6. void increment(Convert &obj)
7. { obj.i=obj.i*2;
8. cout << "Value of i in member function : " << obj.i;
9. }
10. };
11. int main ()
12. { Convert obj1;
13. obj1.i=3; obj1.increment(obj1);
14. cout << "\nValue of i in main : " << obj1.i << "\n";
15. return 0; } 14
Returning Objects
Example 1
#include <iostream> cout << o.get_i() << "\n";
using namespace std; return 0;
class myclass { }
int i;
public: myclass f()
void set_i(int n) { i=n; } {
int get_i() { return i; } myclass x;
}; x.set_i(1);
myclass f(); //return object of return x;
type myclass }

int main()
{ Output:
myclass o;
o = f(); 1

16
• Dynamic Memory Allocation
• Reference Variables

5/5/2025 17
Dynamic Allocation Operators
• new
– Allocates memory and returns a pointer to the start of it. Let p_var
is a pointer variable of any data type type, then
p_var = new type;

• delete
– Frees memory previously allocated using new.
delete p_var;

5/5/2025 18
Operator new Syntax

new DataType

new DataType [IntExpression]

• If memory is available, in an area called the heap (or free


store) new allocates the requested object or array, and
returns a pointer to (address of ) the memory allocated.
• Otherwise, program terminates with error message.
• The dynamically allocated object exists until the delete
operator destroys it.
19
Operator new
2000
char* ptr;
???
5000

ptr

ptr = new char;


5000
*ptr = ‘B’;
‘B’
cout << *ptr;

NOTE: Dynamic data has no variable name

20
The NULL Pointer
• There is a pointer constant called the “null pointer”
denoted by NULL
• But NULL is not memory address 0.
• NOTE: It is an error to dereference a pointer
whose value is NULL. Such an error may cause your
program to crash, or behave erratically. It is the
programmer’s job to check for this.

while (ptr != NULL) {


. . . // ok to use *ptr here
}
21
Operator delete Syntax

delete Pointer

delete [ ] Pointer

• The object or array currently pointed to by Pointer is


deallocated, and the value of Pointer is undefined. The
memory is returned to the free store.
• Good idea to set the pointer to the released
memory to NULL
• Square brackets are used with delete to deallocate a
dynamically allocated array.
22
Operator delete
2000
char* ptr;
5000
???

ptr = new char; ptr

*ptr = ‘B’;
5000
cout << *ptr;
‘B’
delete ptr; NOTE:
delete deallocates the
memory pointed to by ptr

23
Example
char *ptr ;
3000
ptr
ptr = new char[ 5 ]; ???
NULL
6000
???

strcpy( ptr, “Bye” );

ptr[ 0 ] = ‘u’; 6000


‘B’ ‘y’ ‘e’ ‘\0’
‘u’
delete [] ptr; // deallocates the array pointed to by ptr
// ptr itself is not deallocated
ptr = NULL; // the value of ptr becomes undefined

24
Example
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int *p;
6. p = new int(87);
7. cout << "Value is: " << *p;
8. delete p;
9. return 0;
10.}
5/5/2025 25
Some points…
• In case of insufficient memory, new returns null pointer.
• So check for the pointer produced by new before using it.

…..
…..
p = new int;
If(!p)
count << "Allocation failed\n";
…..
…..
5/5/2025 26
Allocating Arrays
Allocate arrays using new by using :
p_var = new array_type [size];
Here, size specifies the number of elements in the
array.

To free an array, use delete:


delete [ ] p_var;
Here, the [ ] informs delete that an array is being
released.

5/5/2025 27
Example
#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p, i;
p= new int[10];
for(i=0; i<10; i++ )
p[i] = i;
for(i=0; i<10; i++)
cout << p[i] << " ";
delete [] p; // release the array
return 0;
}

5/5/2025 28
Allocating Objects
• Allocate objects dynamically by using new.
• An object is created and a pointer is returned to
it.
• The dynamically created object acts just like any
other object. When it is created, its constructor
function (if it has one) is called.
• When the object is freed, its destructor function
is executed.

5/5/2025 29
Example
#include <iostream> int main()
#include <new> {
#include <cstring>
using namespace std; balance *p;
class balance { char s[80];
double cur_bal; double n;
char name[80];
public: p=new balance;
void set(double n, char *s) { p->set(12387.87, "Ralph
cur_bal = n; Wilson");
strcpy(name, s); p->get_bal(n, s);
}
void get_bal(double &n, char *s) cout << s << "'s balance is: " <<
{ n;
n = cur_bal; cout << "\n";
strcpy(s, name); delete p;
}
}; return 0;
}
5/5/2025 30
Advantages
• Automatically computes size of the data object, no need to use sizeof
operator.
• Automatically returns correct pointer type, no need to use type cast.
• Possible to initialize the object during the memory space creation.
• New and delete can be overloaded.

5/5/2025 31
Reference variable
• It provides an alias, an alternative name, for a previously defined
variable.
• Syntax:
data-type &reference-name = variable-name
• Must be initialized at the time of declaration.
• Example:
int x; int n[10];
int *p = &x; int &x = n[10];
int &m = *p; char &a = '\n';
5/5/2025 32
Reference Variables
Reference variable = alias for another variable
- Contains the address of a variable (like a pointer)
- No need to perform any dereferencing (unlike a pointer)
- Must be initialized when it is declared

int x = 5;
int &z = x; // z is another name for x
int &y ; //Error: reference must be initialized
cout << x << endl; -> prints 5
cout << z << endl; -> prints 5

z = 9; // same as x = 9;

cout << x << endl; -> prints 9


cout << z << endl; -> prints 9

33
Why Reference Variables
• Are primarily used as function parameters

• Advantages of using references:


– you don’t have to pass the address of a variable
– you don’t have to dereference the variable inside the
called function

34
Example 1
#include <iostream>
void p_swap(int *a, int *b)
Using namespace std; {
// Function prototypes
(required in C++) int temp;
temp = *a; (2)
void p_swap(int *, int *); *a = *b; (3)
*b = temp;
void r_swap(int&, int&);
}
int main (void){
void r_swap(int &a, int &b)
int v = 5, x = 10;
{
cout << v << x << endl;
int temp;
p_swap(&v,&x);
temp = a; (2)
cout << v << x << endl;
a = b; (3)
r_swap(v,x); b = temp;
cout << v << x << endl; }
return 0;
} 35
Example 2
1. #include <iostream>
2. using namespace std;
3. int main()
4. { int a = 10;
5. int &ref = a;
6. cout << a << " " << ref << endl;
7. ref += 5;
8. cout << a << " " << ref << endl;
9. return 0;
10.}
5/5/2025 36
Example 3
1. #include<iostream>
2. using namespace std;
3. void add(int &n);
4. int main()
5. { int number;
6. number = 34;
7. cout << " The initial value of number : " << number << endl;
8. add(number);
9. cout << " The final value of number : " << number << endl;
10. return(0); }
11. void add(int &n)
12. { n = n + 6; }

5/5/2025 37
Restrictions to References
• Reference to another reference is not possible.
• Address of a reference cannot be obtained.
• Arrays of references cannot be created.
• Pointer to a reference cannot be created.
• Reference for a bit-field is not possible.
• A reference variable must be initialized when it is declared unless it is
a member of a class, a function parameter, or a return value.
• Null references are prohibited.

5/5/2025 38
• Pointers to Objects
• this Pointer
• Pointers to class members

5/5/2025 39
Pointers to Objects

• When accessing members int main()


of a class given a pointer to {
an object, use the arrow cl ob(88), *p;
(–>) operator instead of the p = &ob; // get address of
dot operator. ob
cout << p->get_i(); // use ->
#include <iostream> to call get_i()
using namespace std; return 0;
class cl { }
int i;
public:
cl(int j) { i=j; }
int get_i() { return i; } Output
};
88
5/5/2025 40
Example
int main()
#include <iostream> {
using namespace std; cl ob[3] = {1, 2, 3};
class cl cl *p;
{ int i;
int i; p = ob; // get start of array
public: for(i=0; i<3; i++)
cl() {
{ cout << p->get_i() << "\n";
i=0; p++; // point to next object
} }
cl(int j) return 0;
{ i=j; } }
int get_i() { return i; } Output
};
1
2
5/5/2025
3 41
this pointer
• Member functions of every object have access to a special constant
pointer named this.
• It points to the object itself.
• It is passed automatically as an implicit argument to the invoking
member function.

class ABC class ABC


{ int a; { int a;
public: public:
void set() void set()
{ a = 10; } { this->a = 10; }
}; };
5/5/2025 42
Contd…
• Static member functions do not have 'this' pointer as they can be
called without any object using the class name.
• Not passed to friend functions as they are not member functions of a
class.
• Used when a binary operator is overloaded using a member function.
• Used to return the object it points to.

5/5/2025 43
Example 1

#include <iostream> int main()


using namespace std; { ABC w1, w2;
class ABC w1.reveal();
{ private: w2.reveal();
char charray[10];
cout << endl;
public:
void reveal() return 0;
{ }
cout << "\nMy object's address is " Output
<< this;
My object's address is 0x6ffe40
}
}; My object's address is 0x6ffe30

5/5/2025 44
Example 2
1. #include<iostream>
2. #include<cstring>
3. using namespace std;
4. class person
5. { char name[20];
6. int age;
7. public:
8. void setData(const char *s, int a)
9. { strcpy(name, s);
10. age = a; }
11. person& greater(person &x)
12. { if(x.age >= age) return x;
13. else return *this; }
14. void display()
15. { cout << name << " with age " << age; }
16. };
5/5/2025 45
Contd…
17. int main()
18. { person p1,p2,p3;
19. p1.setData("Abha", 21);
20. p2.setData("Akhil", 29);
21. p3.setData("Mitali", 31);
22. person p = p1.greater(p2);
23. cout << "Elder person is: ";
24. p.display();
25. p = p2.greater(p3);
26. cout << endl << "Elder person is: ";
27. p.display(); Output
28. return 0;
29. } Elder person is: Akhil with age 29
Elder person is: Mitali with age 31
5/5/2025 46
Pointers to Class Members
• A special type of pointer that "points"
generically to a member of a class, not to a
specific instance of that member in an object.
• This sort of pointer is called a pointer to a class
member or a pointer-to-member.
• A pointer to a member is not the same as a
normal C++ pointer. Instead, a pointer to a
member provides only an offset into an object
of the member's class at which that member
can be found.

5/5/2025 47
Contd…..
• Since member pointers are not true pointers, the . and -> cannot be
applied to them.
• To access a member of a class given a pointer to it, use the special
pointer-to-member operators .* and –>*.
• Their job is to allow you to access a member of a class given a pointer
to that member.

5/5/2025 48
Declaring and Assigning Pointer to Data Members of a
Class

5/5/2025 49
Accessing Data Members Using Pointers

5/5/2025 50
Example
#include<iostream> int main()
using namespace std; {
class Test Test t;
{ int Test :: *ptr=&Test::x;
public : t.*ptr=20;
int x; t.show_data();
void show_data(); Test *tp= new Test;
}; tp->*ptr=80;
void Test :: show_data() tp->show_data();
{ return 0;
cout<<“\n x=“<<x; } Output
} X=20
X=80
5/5/2025 51
Pointer to member function

5/5/2025 52
Example 1
int main()
#include <iostream> {
using namespace std; // declare pointer to data member
class X
{
int X::*ptiptr = &X::a;
public: // declare a pointer to member
int a; function
void f(int b) void (X::* ptfptr) (int) = &X::f;
{ // create an object of class type X
cout << "The value of b is "<< b << endl; X xobject;
} // initialize data member
};
xobject.*ptiptr = 10;
cout << "The value of a is " <<
xobject.*ptiptr << endl;
// call member function
(xobject.*ptfptr) (20);
}
Output
The value of a is 10
5/5/2025 53
The value of b is 20
Example 2
#include <iostream> data = &cl::val; // get offset of
using namespace std; val
class cl func = &cl::double_val; // get
{ offset of double_val()
public: cout << "Here are values: ";
cl(int i) { val=i; } cout << ob1.*data << " " <<
int val; ob2.*data << "\n";
int double_val() cout << "Here they are doubled:
{ return val+val; } ";
}; cout << (ob1.*func)() << " ";
int main() cout << (ob2.*func)() << "\n";
{ return 0;
int cl::*data; // data member }
pointer
int (cl::*func)(); // function
member pointer Output
cl ob1(1), ob2(2); // create objects Here are values: 1 2
Here they are doubled: 2 4
5/5/2025 54
Thank You!

55
1. const Member Function
2. Static Object
3. Copy constructor
‘const’ member function
int main(){
const int i = 10;
const int j = i + 10; // works fine
i++; // this leads to Compile time error
}
Const class variable
class Test{
const int i;
public:
Test(int x):i(x) {} //initialized using constructor
void show(){cout<<"i="<<i<<endl;}
};
int main(){Test t(190);t.show(); }
Const function
• The idea of const functions is not to allow
them to modify the object on which they are
called.
• It is recommended to make as many functions
const as possible so that accidental changes to
objects are avoided.
Const class member function
class A{
public: int x;
void func() const{
x = 0; // [Error] can’t modify
object variable
}
};
int main(){}
void Date::setMonth( int mn )
// constant_member_function {
#include<iostream> month = mn; // Modifies data member
using namespace std; }
class Date int main()
{ {
public: Date MyDate( 7, 4, 1998 );
Date( int mn, int dy, int yr ) const Date BirthDate( 1, 18, 1953 );
{ MyDate.setMonth(4); // Okay
month = mn; cout<<MyDate.getMonth();
day = dy; cout<<BirthDate.getMonth(); // Okay
year = yr; //BirthDate.setMonth( 4 ); // C2662 Error
} }
int getMonth() const; // A read-only function
void setMonth( int mn ); // A write function; can't be const
private:
int month,day,year;
};

int Date::getMonth() const


{
return month; // Doesn't modify anything
}
Static Object
What is the output?
class Test {
public: Test() {cout << "In constructor"<<endl; }
~Test() { cout << "In destructor"<<endl; }
};
void myfunc() { Test obj; }
int main() {
cout << "Start main()"<<endl; myfunc();
cout << "End main()"<<endl;
}
Answer:
Start main()
In constructor
In destructor
End main()
Now using static object
class Test {
public: Test() {cout << "In constructor"<<endl; }
~Test() { cout << "In destructor"<<endl; }
};
void myfunc() { static Test obj; }
int main() {
cout << "Start main()"<<endl; myfunc();
cout << "End main()"<<endl;
}
Answer: Static objects never die easily
Start main()
In constructor
End main()
In destructor
Parameterized constructor

• Constructor that take arguments are called parameterized


constructor.
• We must pass the initial values as arguments to the
constructor function when an object is declared , in two ways
1. Calling the constructor Explicitly
2. Calling the Constructor Implicitly
Example of Parameterized Constructor

class example When a constructor is parameterized, we


{ must pass the initial values as arguments to
private: the constructor function when an object is
int a;
declared.
public:
example(int); //Parameterized Constructor Two ways Calling:
void display( ); • 1. Explicit
}; • example e1 = example(5);
example :: example(int x) • 2. Implicit
{ • example e1(5);
a=x;
• //Shorthand method method
}
void example :: display()
{
cout<<a;
}
Example of Parameterized Constructor

#include<iostream> main()
using namespace std; {
class integer integer n1(10,20);
{ integer n2= integer(20,30);
int m,n; n1.display();
public: n2.display();
integer(int , int); }
display();
{ 1. Explicit
cout<<m<<n; integer n2 = example(20,30);
} 2. Implicit
}; integer n1(10,20);
integer :: integer(int x, int y) //Shorthand method
{
m=x; n=y;
}
Copy Constructor

▪ A copy constructor is used to declare and initialize an object


from another object.

▪ For example, the statement:


example e2(e1);
will define the object e2 and at the same time initialize it to
the value of e1.

▪ The process of initializing through a copy constructor is


known as copy initialization.
Example of Copy Constructor
#include<iostream> void example::display()
using namespace std; {
class example cout<<a;
{ }
private:
int main()
int a; {
public: example e1(5);
example(int); //Parameterized Constructor example e2(e1); //or, example e2=e1;
example(example &); //Copy Constructor e2.display();
return 0;
void display();
}
};
example::example(int x) OUTPUT
{ 5
a=x;
}
example::example(example &p)
We cannot pass the argument by value to a
{ copy constructor.
a=p.a;
}
UTA018
Inheritance

1
Inheritance
• Inherit Definition -
Derive quality and characteristics from parents or ancestors. Like
you inherit features of your parents.
• Example:
"She had inherited the beauty of her mother"
• Inheritance in Object Oriented Programming can be described as a
process of creating new classes from existing classes.

2
Inheritance (Cont…)
• New classes inherit some of the properties and behaviour of
the existing classes.
• The existing class that is "parent" of a new class is called a base
class.
• New class that inherits properties of the base class is called
a derived class(“child class”).
• Inheritance is a technique of code reuse.

3
Example: Insect Taxonomy

4
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

5
Base Class access control
• Derived class can be declared from a base
class with different access control, i.e., public
inheritance, protected inheritance or private
inheritance.

6
Protected Members and Class Access

• Protected member access specification: like private, but


accessible by objects of derived class
• Class access specification: determines how private,
protected, and public members of base class are
inherited by the derived class

7
Class Access Specifiers
public – object of derived class can be treated as object of base
class (not vice-versa)
protected – more restrictive than public, but allows derived
classes to know details of parents
private – prevents objects of derived class from being treated as
objects of base class.

8
Syntax
1. #include <iostream>
2. using namespace std;
3. class base
4. { .... ... .... };
5. class derived : access_specifier base
6. { .... ... .... };

• Either public, protected or private keyword is


used in place of access_specifier term used in
the syntax code code.
9
1.class base {
2. public: int x;
3. protected: int y;
4. private: int z; };
5. class publicDerived: public base {
6. // x is public
7. // y is protected
8. // z is not accessible from publicDerived };
9. class protectedDerived: protected base {
10. // x is protected
11. // y is protected
12. // z is not accessible from protectedDerived };
13. class privateDerived: private base {
14. // x is private
15. // y is private
16. // z is not accessible from privateDerived }

10
Observations
• base class has three member variables: x, y and
z which are public, protected and private
member respectively.
• publicDerived inherits variables x and y as
public and protected. z is not inherited as it is a
private member variable of base class.
• protectedDerived inherits variables x and y.
Both variables become protected. z is not
inherited.

11
Observations (Cont…)
• If we derive a class
derivedFromProtectedDerived from
protectedDerived, variables x and y are also
inherited to the derived class.
• privateDerived inherits variables x and y. Both
variables become private. z is not inherited
• If we derive a class derivedFromPrivateDerived
from privateDerived, variables x and y are not
inherited because they are private variables of
privateDerived.

12
Accessibility in Public Inheritance

13
Accessibility in Protected Inheritance

14
Accessibility in Private Inheritance

15
Inheritance vs. Access
How inherited base class
members
Base class members appear in derived class
private: x private x is inaccessible
protected: y base class
private: y
public: z private: z

private: x protected x is inaccessible


protected: y base class protected: y
public: z protected: z

private: x public x is inaccessible


protected: y base class protected: y
public: z public: z
16
Inheritance vs. Access
class Grade class Test : public Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
public class access, it public members:
Test(int, int);
looks like this: void setScore(float);
float getScore();
char getLetter();

17
Inheritance vs. Access
class Grade class Test : protected Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
protected class access, it public members:
Test(int, int);
looks like this: protected members:
void setScore(float);
float getScore();
float getLetter();

18
Inheritance vs. Access
class Grade class Test : private Grade
private members: private members:
char letter; int numQuestions;
float score; float pointsEach;
void calcGrade(); int numMissed;
public members: public members:
void setScore(float); Test(int, int);
float getScore();
char getLetter();
private members:
int numQuestions:
When Test class inherits float pointsEach;
from Grade class using int numMissed;
private class access, it void setScore(float);
float getScore();
looks like this: float getLetter();
public members:
Test(int, int);

19
What Does a Child Have?
An object of the derived class has:
• all members defined in child class
• all members declared in parent class

An object of the derived class can use:


• all public members defined in child class
• all public members defined in parent class

20
Types of Inheritance

21
Thanks

22
Types of Inheritance

23
Single Inheritance
• Single Inheritance: It is the inheritance
hierarchy wherein one derived class inherits
from one base class.

24
Single Inheritance Syntax

25
Single Inheritance Example
1. #include <iostream.h>
2. using namespace std;
3. class Shape { Output
4. protected:
5. int width;
6. int height;
7. public:
8. void setWidth(int w) {
9. width = w; }
10. void setHeight(int h) {
11. height = h; } } ;
12. class Rectangle: public Shape {
13. public:
14. int getArea() {
15. return (width * height); } }
16. int main {
17. Rectangle Rect;
18. Rect.setWidth(5);
19. Rect.setHeight(7);
20. cout << "Total area: " << Rect.getArea() << endl; // Print the area of the object.
21. return 0;
22. }

26
#include <iostream.h> int main()
using namespace std; {
class base { derived ob(3);
int i, j; ob.set(1, 2); // access member of
public: base
void set(int a, int b) ob.show(); // access member of
{ i=a; j=b; } base
void show() ob.showk(); // uses member of
derived class
{ cout << i << " " << j << "\n"; } return 0;
}; }
class derived : public base {
int k;
public:
derived(int x) { k=x; }
void showk() { cout << k << "\n";
}
};

27
// This program won't public:
compile. derived(int x) { k=x; }
#include <iostream.h> void showk()
using namespace std; { cout << k << "\n"; }
class base { };
int i, j; int main()
public: {
void set(int a, int b) { i=a; j=b; derived ob(3);
} ob.set(1, 2);
void show() { cout << i << " " // error, can't access set()
<< j << "\n";}
}; ob.show();
// Public elements of base are // error, can't access show()
private in derived. return 0;
class derived : private base { }
int k;

28
Multiple Inheritance
• Multiple Inheritance: It is the inheritance
hierarchy wherein one derived class inherits
from multiple base class(es).

29
Syntax

30
Inheriting Multiple Base Classes
#include <iostream> // Inherit multiple base classes.
using namespace std; class derived: public base1, public
class base1 { base2 {
protected: public:
int x; void set(int i, int j) { x=i; y=j; }
public: };
void showx() { cout << x << "\n"; } int main()
}; {
class base2 { derived ob;
protected: ob.set(10, 20);
int y; // provided by derived
Public: ob.showx(); // from base1
void showy() {cout << y << "\n";} ob.showy(); // from base2
}; return 0;
}

31
//EXAMPLE // Derived class
#include <iostream.h> class Rectangle: public Shape, public
using namespace std; PaintCost {
// Base class Shape
public:
class Shape {
public: int getArea() {
void setWidth(int w) { return (width * height);
width = w; } } };
void setHeight(int h) { int main(void) {
height = h; }
Rectangle Rect;
protected:
int width; int area;
int height; Rect.setWidth(5);
}; Rect.setHeight(7);
// Base class PaintCost area = Rect.getArea();
class PaintCost {
// Print the total cost of painting
public:
int getCost(int area) { cout << "Total paint cost: $" <<
return area * 70; Rect.getCost(area) << endl;
}}; return 0; }
32
Multilevel Inheritance
• Multilevel Inheritance: It is the inheritance
hierarchy wherein subclass acts as a base class
for other classes.

33
Syntax

34
Multi-level Inheritance
#include <iostream> //derived2 class
using namespace std; class derived2 : public derived
//Base class { public:
class base { void display3(){
public: cout << "\n2nd Derived class
void display1() { content.";
cout << "\nBase class content."; } } };
}; int main()
//derived class {
class derived : public base derived2 D;
{ D.display3();
public: D.display2();
void display2() D.display1();
{ return(0);
cout << "1st derived class content."; }
} };

35
Hierarchical Inheritance
• Hierarchical Inheritance: It is the inheritance
hierarchy wherein multiple subclasses inherit
from one base class.

36
Hierarchical Inheritance

37
Hierarchical Inheritance
#include <iostream> void disp() {
#include <string.h> cout << "Age: " << age <<
using namespace std; endl; cout << "Gender: "
//Base Class << gender << endl; }
class member { };
char gender[10]; //derived from member
int age; class stud : public member
public: { char level[20];
void get() public:
{ cout << "Age: "; cin >> age; void getdata() {
member::get();
cout << "Gender: "; cin >> cout << "Class: ";
gender; }
cin >> level; }
Continue...

38
void disp2() void disp3() {
{ member::disp(); member::disp();
cout << "Level: " << level; cout << "Salary: Rs." <<
} }; salary << endl;
//staff class derived from } };
member
class staff : public member int main() {
{ float salary; //member M;
public: staff S;
void getdata() { stud s;
member::get(); s.getdata();
cout << "Salary: Rs."; s.disp();
cin >> salary; } S.getdata();
S.disp();
return(0); }

39
Hybrid Inheritance
• Hybrid Inheritance: The inheritance hierarchy
that reflects any legal combination of other
four types of inheritance.

40
Syntax

41
#include <iostream> class D : public B, public C
using namespace std; //D is derived from class B and
class A { class C
public: int x; { public:
}; void sum()
class B : public A { { cout << "Sum= " << x + y; }
public: B() //constructor to };
initialize x in base class A int main()
{ x = 10; } { D obj1; //object of derived
}; class D
class C { obj1.sum();
public: int y; C() //constructor to return 0; Output
initialize y { y = 4; } }
};
42
Thanks

43
Inheritance - 2

1
Content
• Constructor and Destructor in Inheritance
• Inheritance and Static Functions
• Virtual class
• Abstract Class
• Pure Virtual Functions
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.

3
//EXAMPLE ~derived()
#include<iostream> { cout << "Destructing derived\n"; }
Using namespace std; };
//base class int main()
class base { {
public: derived ob;
base() // do nothing but construct and
{ cout << "Constructing base\n"; } destruct ob
return 0;
~base()
{ cout << "Destructing base\n"; } }
};
//derived class
class derived: public base { Program Output
public: Constructing base
Constructing derived
derived()
Destructing derived
{ Destructing base
cout << "Constructing derived\n"; }

4
Constructors and Destructors with Multiple Base
Classes
• Constructors are called in order of derivation, left to right, as
specified in derived's inheritance list.
• Destructors are called in reverse order, right to left.

5
//MULTI-LEVEL class derived2: public derived1 {
#include <iostream> public:
using namespace std; derived2() { cout <<
class base { "Constructing derived2\n"; }
public: ~derived2() { cout <<
"Destructing derived2\n"; }
base() };
{ cout << "Constructing base\n"; int main()
}
~base() { cout << "Destructing {
base\n"; } derived2 ob;
}; // construct and destruct ob
class derived1 : public base { return 0;
public: } Program Output:
derived1() { cout << Constructing base
"Constructing derived1\n"; } Constructing derived1
~derived1() { cout << Constructing derived2
"Destructing derived1\n"; } Destructing derived2
}; Destructing derived1
Destructing base
6
//MULTIPLE BASE CASES class derived: public base1, public
#include <iostream> base2 {
using namespace std; public:
class base1 { derived() { cout << "Constructing
derived\n"; }
public: ~derived() { cout << "Destructing
base1() { cout << "Constructing derived\n"; }
base1\n"; } };
~base1() { cout << "Destructing int main()
base1\n"; }
}; {
class base2 { derived ob;
public: // construct and destruct ob
base2() { cout << "Constructing return 0;
base2\n"; } } Program Output:
Constructing base1
~base2() { cout << "Destructing Constructing base2
base2\n"; } Constructing derived
}; Destructing derived
Destructing base2
Destructing base1
7
Passing Arguments to Base Class Constructor
derived-constructor(arg-list) : base1(arg-list),
base2(arg-list),
// ...
baseN(arg-list)
{
// body of derived constructor
}

8
Order of Constructor Call
• Base class constructors are always called in the derived class
constructors.
• Whenever you create derived class object, first the base class default
constructor is executed and then the derived class's constructor
finishes execution.

9
//EXAMPLE // derived uses x; y is passed
#include <iostream> along to base.
using namespace std; derived(int x, int y): base(y)
class base { { j=x;
protected: cout << "Constructing
derived\n"; }
int i; ~derived() { cout << "Destructing
public: derived\n"; }
base(int x) void show() { cout << i << " " << j
<< "\n"; }
{ i=x; cout << "Constructing
base\n"; } };
~base() { cout << "Destructing int main()
base\n"; } {
}; derived ob(3, 4);
class derived: public base { ob.show(); // displays 4 3
int j; return 0;
public: }

10
//MULTIPLE BASE CASES class derived: public base1, public
#include <iostream> base2 {
int j;
using namespace std;
class base1 { public:

protected: int i; derived(int x, int y, int z): base1(y),


base2(z)
public:
{ j=x; cout << "Constructing
base1(int x) { i=x; cout << derived\n"; }
"Constructing base1\n"; }
~derived() { cout << "Destructing
~base1() { cout << "Destructing derived\n"; }
base1\n"; }};
void show() { cout << i << " " << j <<
class base2 { " " << k << "\n"; }
protected: int k; };
public: int main()
base2(int x) { k=x; cout << { derived ob(3, 4, 5);
"Constructing base2\n"; }
ob.show(); // displays 4 3 5
~base2() { cout << "Destructing
base1\n"; } }; return 0; }
11
Here’s what actually happens when base is instantiated:

• Memory for base is set aside


• The appropriate Base constructor is called
• The initialization list initializes variables
• The body of the constructor executes
• Control is returned to the caller

12
Here’s what actually happens when derived is instantiated:

• Memory for derived is set aside (enough for both the Base and
Derived portions)
• The appropriate Derived constructor is called
• The Base object is constructed first using the appropriate Base
constructor. If no base constructor is specified, the default
constructor will be used.
• The initialization list initializes variables
• The body of the constructor executes
• Control is returned to the caller

13
Points to note
• It is important to understand that arguments to a base-class
constructor are passed via arguments to the derived class' constructor.

• Even if a derived class‘ constructor does not use any arguments, it will
still need to declare one if the base class requires it.

• In this situation, the arguments passed to the derived class are simply
passed along to the base.

14
Why is Base class Constructor called inside Derived class?
• Constructors have a special job of initializing the object properly.
• A Derived class constructor has access only to its own class members,
but a Derived class object also have inherited property of Base class,
and only base class constructor can properly initialize base class
members.
• Hence all the constructors are called, else object wouldn't be
constructed properly.

15
// This program contains an int main() {
error and will not compile. derived3 ob;
#include <iostream> ob.i = 10; // this is
ambiguous, which i???
using namespace std;
ob.j = 20;
class base {
ob.k = 30;
public: int i; }; // i ambiguous here, too
class derived1 : public base { ob.sum = ob.i + ob.j + ob.k;
public: int j; }; // also ambiguous, which i?
class derived2 : public base { cout << ob.i << " ";
public: int k; }; cout << ob.j << " " << ob.k ;
class derived3 : public
cout << ob.sum;
derived1, public derived2 { return 0;
public: int sum; }; }

16
Discussion
• which ‘i’ is being referred to, the one in derived1 or the one in
derived2?
• Because there are two copies of base present in object ob, there are
two ob.is! ->, the statement is inherently ambiguous.
• There are two ways to remedy the preceding program.
• The first is to apply the scope resolution operator to i and manually
select one i. Example (on next slide).

17
// This program uses explicit int main()
scope resolution to select i. {
#include <iostream>
derived3 ob;
using namespace std;
ob.derived1::i = 10; // scope
class base { public: int i; }; resolved, use derived1's i
// derived1 inherits base. ob.j = 20;
class derived1 : public base { ob.k = 30;
public: int j; }; // scope resolved
// derived2 inherits base. ob.sum = ob.derived1::i + ob.j +
class derived2 : public base { ob.k;
public: int k; }; // also resolved here
class derived3 : public cout << ob.derived1::i << " ";
derived1, public derived2 { cout << ob.j << " " << ob.k << " ";
public: int sum; }; cout << ob.sum;
return 0; }
18
Discussion
• As you can see, because the :: was applied, the program has
manually selected derived1's version of base.
• What if only one copy of base is actually required? Is there some way
to prevent two copies from being included in derived3?
• This solution is achieved using virtual base classes.

20
• When two or more objects are derived from a common base class, you
can prevent multiple copies of the base class from being present in an
object derived from those objects by declaring the base class as virtual
when it is inherited.
• You accomplish this by preceding the base class' name with the
keyword virtual when it is inherited.
• For example, here is another version of the example program in which
derived3 contains only one copy of base:

Example Program Next


Slide

21
// This program uses virtual base classes. int main()
#include <iostream>
using namespace std;
{
class base { public: int i; }; derived3 ob;
ob.i = 10; // now unambiguous
// derived1 inherits base as virtual.
ob.j = 20;
class derived1 : virtual public base { ob.k = 30;
public: int j; }; // unambiguous
// derived2 inherits base as virtual. ob.sum = ob.i + ob.j + ob.k;
// unambiguous
class derived2 : virtual public base { cout << ob.i << " ";
public: int k; };
cout << ob.j << " " << ob.k << " ";
class derived3 : public derived1, public cout << ob.sum;
derived2
{ public: int sum; }; return 0;
}
22
Discussion
• As you can see, the keyword virtual precedes the rest of the inherited
class‘specification.
• Now that both derived1 and derived2 have inherited base as virtual,
any multiple inheritance involving them will cause only one copy of
base to be present.
• Therefore, in derived3, there is only one copy of base and ob.i = 10 is
perfectly valid and unambiguous.

23
Inheritance and Static Functions

• They are inherited into the derived class.


• If you redefine a static member function in derived class, all the other
overloaded functions in base class are hidden.
• Static Member functions can never be virtual.

24
Virtual base class
• They are used to prevent the confusion or duplicity among child
classes during inheritance.
• Consider the following situation:
class A {
public: void show() {cout<<"In A"<<endl;}
};

class B : public A {};


class C : public A {};
class D : public B, public C {};

int main() {D d; d.show(); }


Output

[Error] request for member 'show' is ambiguous

Need virtual keyword to fix this error


class A {
public: void show() {cout<<"In A"<<endl;}
};

class B : public virtual A {};


class C : public virtual A {};
class D : public B, public C {};

int main() {D d; d.show(); }


Abstract base class - interface
• It describes the capabilities of a C++ class without committing to a
particular implementation
• A class is made abstract by declaring at least one of its functions
as pure virtual function i.e. by placing "= 0" in its declaration
class Animal{
public:
virtual void sound() = 0;
void sleeping() {cout<<"Sleeping"; }
};
class Dog: public Animal{
public:
void sound() {cout<<"Woof"<<endl;}
};

int main(){
Dog obj; obj.sound(); obj.sleeping();
}
Output:
Woof

Sleeping
class Animal{
public:
virtual void sound() = 0;
void sleeping() {cout<<"Sleeping"; }
};
class Dog: public Animal{
public:
void sound() {cout<<"Woof"<<endl;}
};

int main(){
Animal *obj = new Dog;
obj->sound();
}
Output:
Woof
Abstract Class
• An abstract class is designed to act as base class. It is a design concept
in program development and provides a base upon which other
classes may be built.
• Abstract Class is a class which contains atleast one Pure Virtual
function in it. Abstract classes are used to provide an Interface for its
sub classes. Classes inheriting an Abstract Class must provide
definition to the pure virtual function, otherwise they will also
become abstract class.

34
Characteristics of Abstract Class
• Abstract class cannot be instantiated, but pointers and references of
Abstract class type can be created.
• Abstract class can have normal functions and variables along with a
pure virtual function.
• Classes inheriting an Abstract Class must implement all pure virtual
functions, or else they will become Abstract too.

35
Pure Virtual Functions
• Pure virtual Functions are virtual functions with no definition.
• They start with virtual keyword and ends with = 0.
• Syntax for a pure virtual function,
virtual void fun() = 0;

36
//Abstract base class int main()
class Base { {
public: //Base obj; (Compile Time
virtual void show() = 0; }; Error)
class Derived:public Base { Base *b;
public: Derived d;
void show() b = &d;
{ b->show();
cout << "Implementation of return 0;
Virtual Function in Derived }
class";
}
};

37
Note:
• Pure Virtual functions can be given a small definition in the Abstract
class, which you want all the derived classes to have. Still you cannot
create object of Abstract class.
• Also, the Pure Virtual function must be defined outside the class
definition. If you will define it inside the class definition, complier will
give an error. Inline pure virtual definition is Illegal.

38
Polymorphism
Contents
• Polymorphism
• Function Overloading
• Default Function Arguments
• Ambiguity in Function Overloading
Polymorphism
• 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.
Types of Polymorphism
• Compile Time Polymorphism
• Run Time Polymorphism
Compile Time Polymorphism
• Early binding refers to events that occur at compile time. In essence, early
binding occurs when all information needed to call a function is known at
compile time. (Put differently, early binding means that an object and a function
call are bound during compilation).
• Examples of early binding include normal function calls (including standard
library functions), overloaded function calls, and overloaded operators.
• The main advantage to early binding is efficiency. Because all information
necessary to call a function is determined at compile time, these types of
function calls are very fast.
Run Time Polymorphism
• The opposite of early binding is late binding.
• As it relates to C++, late binding refers to function calls that are not
resolved until run time.
• As function calls are not determined at compile time, the object and the
function are not linked until run time.
Run Time Polymorphism
• The main advantage to late binding is flexibility.
• Unlike early binding, late binding allows you to create programs that
can respond to events occurring while the program executes without
having to create a large amount of "contingency code."
• Keep in mind that because a function call is not resolved until run time,
late binding can make for somewhat slower execution times.
• Virtual functions are used to achieve late binding.
Function Overloading
• Function overloading is the process of using the same name for
two or more functions.
• The secret to overloading is that each redefinition of the function
must use either different types of parameters or a different number
of parameters.
• It is only through these differences that the compiler knows which
function to call in any given situation.
Example
#include <iostream>
using namespace std;
int myfunc(int i); // these differ in types of parameters
double myfunc(double i);
int main()
{
cout << myfunc(10) << " "; // calls myfunc(int i)
cout << myfunc(5.4); // calls myfunc(double i)
return 0;
}
double myfunc(double i)
{
return i;
}
Output:
int myfunc(int i) 10 5.4
{
return i;
}
Example 2
#include <iostream>
using namespace std;
int myfunc(int i); // these differ in number of parameters
int myfunc(int i, int j);
int main()
{
cout << myfunc(10) << " "; // calls myfunc(int i)
cout << myfunc(4, 5); // calls myfunc(int i, int j)
return 0;
}
int myfunc(int i)
{
return i;
}
Output:
int myfunc(int i, int j) 10 20

{
return i*j;
}
Key Points
• The key point about function overloading is that the functions must differ in regard to the types
and/or number of parameters. Two functions differing only in their return types cannot be
overloaded.
• For example, this is an invalid attempt to overload myfunc( ):
int myfunc(int i);
float myfunc(int i);
// Error: differing return types are insufficient when overloading.
• Sometimes, two function declarations will appear to differ, when in
fact they do not. For example, consider the following declarations.
void f(int *p);
void f(int p[]); // error, *p is same as p[]
• Remember, to the compiler *p is the same as p[ ]. Therefore, although the two prototypes appear
to differ in the types of their parameter, in actuality they do not.
Example 3
Example 4
(Function overloading in classes)
Inheritance based Polymorphism
Example
Extend the Logic
Virtual Functions
• Be aware that the virtual function mechanism works only with
pointers to objects and, with references, not with objects themselves.
Class Activity (15 minutes)
• Can you showcase polymorphism (Drive function in various types
of automobiles) in context of VEHICLES ?
Overloading vs overriding
• Function overloading – same function name but
different arguments. Functions are defined in the
same class.

• Function overriding – same function name and


arguments. Defined in different classes.
Compile time and Run time Polymorphism
• Compile time OR static polymorphism is executed
using function overloading.

• Run time polymorphism or dynamic/late binding is


done using function overriding and virtual functions.
Compile Time Polymorphism Run-Time Polymorphism
At Compile time, which functions to be At Runtime, which function to be
called is decided. called is decided.

Also known as early or static binding Also known as late or dynamic binding

It executes faster because the function It executes slower because the function
is resolved at compilation time only. is resolved at Run-time.

It is achieved through function and It is achieved through function


operator overloading overriding and virtual functions
Default Function Arguments
• C++ allows a function to assign a parameter a default value when
no argument corresponding to that parameter is specified in a call
to that function.
• For example, this declares myfunc( ) as taking one double argument
with a default value of 0.0:

void myfunc(double d = 0.0)


{
// ...}

myfunc(198.234); // pass an explicit value


myfunc(); // let function use default
The first call passes the value 198.234 to d. The second call
automatically gives d the default value zero.
• The idea behind default argument is simple. If
a function is called by passing argument/s,
those arguments are used by the function.
• But if the argument/s are not passed while
invoking a function then, the default values
are used.
• Default value/s are passed to argument/s in
the function prototype.
Example
Rules for using Default Arguments
Common Mistakes when using Default
Arguments
Ambiguity in Function Overloading
• You can create a situation in which the
compiler is unable to choose between two (or
more) overloaded functions.
• When this happens, the situation is said to be
ambiguous.
• Ambiguous statements are errors, and
programs containing ambiguity will not
compile.
Ambiguity in Function Overloading
int myfunc(double d);
// ...
cout << myfunc('c');
// not an error, conversion applied
• Although automatic type conversions are
convenient, they are also a prime cause of
ambiguity.
Example
#include <iostream>
using namespace std;
float myfunc(float i);
double myfunc(double i);

int main()
{
cout << myfunc(10.1) << " "; // unambiguous, calls
myfunc(double)
cout << myfunc(10); // ambiguous
return 0;
}
Thanks
Operator Overloading
Introduction

• Operator overloading
➢ Enabling C++’s operators to work with class objects
➢ Using traditional operators with user-defined objects
➢ Examples of already overloaded operators
• Operator << is both the stream-insertion operator and the
bitwise left-shift operator
• Operator >> is both the stream-extraction operator and the
bitwise right-shift operator
➢ Compiler generates the appropriate code based on the
manner in which the operator is used.
Introduction (Cont…)
• Overloading an operator
– Write function definition as normal
– Functionname is keywordoperator followed bythe symbol for the
operator being overloaded
– For e.g., operator+ used to overload the addition operator
(+)
• Using operators
– To use an operator on a class object, it must be overloaded unless the
assignment operator (=) or the address operator (&)
• Assignment operator by default performs memberwise assignment
• Address operator (&) by default returns the address of an object
Restrictions on Operator Overloading
• Overloading restrictions
– Precedence of an operator cannot be changed
– Associativity of an operator cannot be changed
– number of operands cannot be changed
• Unary operators remain unary, and binary operators remain binary
• Operators &, *, + and - each have unary and binary versions
• Unary and binary versions can be overloaded separately
• No new operators can be created
– Use only existing operators
• No overloading operators for built-in types
– Cannot change how two integers are added
– Produces a syntax error
What are Operators in C++?
• Arithmetic Operators: +, −, /, ∗, %
• Assignment Operators: +=,+=, −=,−=, /=,/=, ∗=,∗=, %=%=
• Relational Operators: ==,==, !=,!=, >=,>=, <=,<=,etc.
• Logical Operators: &&,&&, ∣∣,∣∣, !!
• Bitwise Operators: &,&, ∣,∣, >>, <<etc.
• Other Operators: sizeof, ?:,etc.
Restrictions on Operator Overloading
• All the C++ operators can be overloaded except the following:
• Scope Resolution Operator (::)
• Conditional Operator (? :)
• Size Operator (sizeof)
• Class Member Access Operators (. and .*)
Operator Functions as Class Members vs. as friend Functions

• Operator functions can be either member or non- member


functions of a class.
• Operator functions as member functions
– Leftmost operand must be an object of the class
• Operator functions as non-member functions
– Must be friend functions of the class
– Enables the operator to be commutative

Note: If left operand is of a different type than class, operator function must be a non-member function
C++ Syntax for Operator Overloading
• class ClassName{

• private:
• ...............

public:
• ...............

• <ReturnType> operator <operator> (arguments){
• ...............
• ...............
• }
• ...............
• };
Creating a Member Operator Function

returntype classname::operator opname(arg-list)


{
// operations
} Keyword
Unary Operators
• The unary operators operate on a single operand and
following are the examples of Unary operators −

➢ The increment (++) and decrement (--) operators.


➢ The unary minus (-) operator.
➢ The logical not (!) operator.
Overloading of Unary Operator - (using member function)
#include <iostream> Distance::Distance()
using namespace std; {
class Distance feet = 0;
{ inches = 0;
private: }
int feet;
int inches; Distance::Distance(int f, int i)
public: {
//Default constructor feet = f;
Distance(); inches = i;
//Parameterized constructor }
Distance(int , int )
// method to display distance void distance::displayDistance()
void distance::displayDistance() ; {
// overloaded unary minus (-) operator cout << "F: " << feet << " I:" << inches <<endl;
Distance operator- () }
};
Continued…
Distance Distance::operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}

int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1; // activates operator-() function
D1.displayDistance(); // D1display Output:
-D2; // activates operator-() function F: -11 I:-10 F: 5 I:-11
D2.displayDistance(); // display D2
return 0;
}
Binary Operators
• The binary operators take two arguments.

• Binary operators are used very frequently like


addition (+) operator, subtraction (-) operator
and division (/) operator.
Overloading Binary Operators
#include <iostream> loc operator+(loc op2);
using namespace std; };
class loc {
int longitude, latitude; // Overload + for loc
public: loc loc::operator+(loc op2)
//constructors {
loc() { loc temp;
} temp.longitude = op2.longitude + longitude;
loc(int lg, int lt) { temp.latitude = op2.latitude + latitude;
longitude = lg; return temp;
latitude = lt; }
}
void show()
{
cout << longitude << " ";
cout << latitude << "\n";
}
Continued…
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1.show(); // displays 10 20
ob2.show(); // displays 5 30
ob1 = ob1 + ob2;
/*equivalent to
Output:
ob1=ob1.operator+(ob2);*/
10 20
ob1.show(); // displays 15 50
5 30
return 0;
15 50
}
Overloading +, -(binary) and ++(unary)
#include <iostream> loc operator+(loc op2);
using namespace std; loc operator-(loc op2);
class loc { loc operator=(loc op2);
int longitude, latitude; loc operator++();
public: };
loc() {} // constructors // Overload + for loc
loc(int lg, int lt) { loc loc::operator+(loc op2)
longitude = lg; {
latitude = lt; loc temp;
} temp.longitude = op2.longitude + longitude;
void show() { temp.latitude = op2.latitude + latitude;
cout << longitude << " "; return temp;
cout << latitude << "\n"; }
}
Continued…
// Overload - for loc int main()
loc loc::operator-(loc op2) {
{ loc ob1(10, 20), ob2( 5, 30), ob3(90, 90);
loc temp; ob1.show();
// notice order of operands ob2.show();
temp.longitude = longitude - op2.longitude; ++ob1;
temp.latitude = latitude - op2.latitude; ob1.show(); // displays 11 21
return temp; ob2 = ++ob1;
} ob1.show(); // displays 12 22
// Overload asignment for loc ob2.show(); // displays 12 22
loc loc::operator=(loc op2) ob1 = ob2 = ob3; // multiple assignment
{ ob1.show(); // displays 90 90
longitude = op2.longitude; ob2.show(); // displays 90 90
latitude = op2.latitude; return 0;
return *this; // i.e., return object that generated call }
} Output:
// Overload prefix ++ for loc 10 20
loc loc::operator++() 5 30
{ 11 21
longitude++; 12 22
latitude++; 12 22
return *this; 90 90
}
Overloading using Friend Functions
• There are certain situations where we would like to use a
friend function rather than a member function.
• For example, if we want to use two different types of a binary
operator, say, one an object and another a built in type as
shown below:
A=B+2, where A and B are objects of same class. This will
work for a member function, but the statement A=2+B; will
not work.
• This is because the left-handed operand which is responsible
for invoking the membership function should be an object of
the same class.
• Friend function allows both approaches as it is invoked
without the use of objects.
Continued…
• Unary operators, overloaded by means of a member function,
take no explicit arguments, but, those overloaded by means
of a friend function, take one reference argument (the object
of the relevant class).

• Binary operators overloaded through a member function take


one explicit argument and those which are overloaded
through a friend function take two explicit arguments.

• When using binary operators overloading through member


function, the left hand operand must be an object of the
relevant class.
Example
#include <iostream> friend loc operator+(loc op1, loc op2);
using namespace std; // now a friend
class loc { };
int longitude, latitude; /*Now, + is overloaded using friend function*/
public: loc operator+(loc op1, loc op2)
loc() {} // constructors {
loc(int lg, int lt) { loc temp;
longitude = lg; temp.longitude = op1.longitude + op2.longitude;
latitude = lt; temp.latitude = op1.latitude + op2.latitude;
} return temp;
void show() { }
cout << longitude << " ";
cout << latitude << "\n";
}
Continued…
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
} Output:
15 50
Restrictions on application of friend function
• Operators that can not be overloaded using a friend
function are:
= Assignment operator
() Function call operator
[] Subscript operator
-> Class Member Access Operator
Overloading new and delete
// Allocate an object // Delete an object
void *operator new(size_t void operator delete(void
size) *p)
{ {
/* Perform allocation. /* Free memory pointed to
Throw bad_alloc on failure. by p.
Constructor called Destructor called
automatically. */ automatically. */
return pointer_to_memory; }
}
Example
#include <iostream> // new overloaded relative to loc
using namespace std; void *loc::operator new(size_t size)
class loc { {
int longitude, latitude; void *p;
public: cout << "In overloaded new.\n";
loc() {} p = malloc(size);
loc(int lg, int lt) return p;
longitude = lg; }
latitude = lt; // delete overloaded relative to loc
} void loc::operator delete(void *p)
void show() { {
cout << longitude << " "; cout << "In overloaded delete.\n";
cout << latitude << "\n"; free(p);
} }
void *operator new(size_t size);
void operator delete(void *p);
};
Continued…
int main()
{
loc *p1, *p2;

p1 = new loc (10, 20);


p2 = new loc (-10, -20);
}
p1->show();
p2->show();
delete p1;
delete p2;
return 0;
}
Overloading [ ] operator
• In C++, the [ ] is considered a binary operator when you are
overloading it.

• Therefore, the general form of a member operator[ ]( ) function is as


shown here:
returntype classname::operator[](int i)
{
// . . .
}

• Technically, the parameter does not have to be of type int, but an


operator[ ]( ) function is typically used to provide array subscripting,
and as such, an integer value is generally used.

• Given an object called obj, the expression obj[3] translates into this
call to the operator[ ]( ) function: obj.operator[](3)
Example 1
#include <iostream> int operator[](int i)
using namespace std; { return a[i];
class atype { }
int a[3]; };
public: int main()
atype(int i, int j, int k) { {
a[0] = i; atype ob(1, 2, 3);
a[1] = j; cout << ob[1]; // displays 2
a[2] = k; return 0;
} } Output:
2
Example 2
#include <iostream> int main()
using namespace std; {
class atype { atype ob(1, 2, 3);
int a[3]; cout << ob[1]; // displays 2
public: cout << " ";
atype(int i, int j, int k) { ob[1] = 25; // [] on left of =
a[0] = i; cout << ob[1]; // now displays 25
a[1] = j; return 0;
a[2] = k; }
}
Output:
int &operator[](int i) {
return a[i]; 2 25
}
};
Overloading ()
• When we overload the ( ) function call operator, we are
not creating a new way to call a function.

• Rather, you are creating an operator function that can be


passed an arbitrary number of parameters.

Example:
double operator()(int a, float f, char *s);
and an object O of its class, then the statement
O(10, 23.34, "hi");
translates into this call to the operator( ) function.
O.operator()(10, 23.34, "hi");
Example
#include <iostream>
using namespace std; // Overload + for loc
class loc { loc loc::operator+(loc op2)
int longitude, latitude; {
public: loc temp;
loc() {} temp.longitude = op2.longitude + longitude;
loc(int lg, int lt) temp.latitude = op2.latitude + latitude;
{ return temp;
longitude = lg; }
latitude = lt;
}
void show() { int main()
cout << longitude << " "; {
cout << latitude << "\n"; loc ob1(10, 20), ob2(1, 1);
} ob1.show();
loc operator+(loc op2); ob1(7, 8); // can be executed by itself
loc operator()(int i, int j); ob1.show();
}; ob1 = ob2 + ob1(10, 10); // can be used in expressions
// Overload ( ) for loc ob1.show();
loc loc::operator()(int i, int j) return 0;
{ }
longitude = i;
latitude = j;
return *this;
}
Overloading the Comma Operator
#include <iostream> cout << op2.longitude << " " << op2.latitude << "\n";
using namespace std; return temp;
class loc { }
int longitude, latitude; // Overload + for loc
public: loc loc::operator+(loc op2)
loc() {} {
loc(int lg, int lt) { loc temp;
longitude = lg; temp.longitude = op2.longitude + longitude;
latitude = lt; temp.latitude = op2.latitude + latitude;
} return temp;
void show() { }
cout << longitude << " "; int main()
cout << latitude << "\n"; {
} loc ob1(10, 20), ob2( 5, 30), ob3(1, 1);
loc operator+(loc op2); ob1.show();
loc operator,(loc op2); ob2.show();
}; ob3.show();
// overload comma for loc cout << "\n";
loc loc::operator,(loc op2) ob1 = (ob1, ob2+ob2, ob3);
{ ob1.show(); // displays 1 1, the value of ob3
loc temp; return 0;
temp.longitude = op2.longitude; }
temp.latitude = op2.latitude;
Overloading ->
• The –> pointer operator, also called the class member access operator,
is considered a unary operator when overloading.

• Its general usage is shown here:


object->element;
• Here, object is the object that activates the call. The operator–>( )
function must return a pointer to an object of the class that operator–>(
) operates upon.

• The element must be some member accessible within the object.

• The example illustrates overloading the –> by showing the equivalence


between ob.i and ob–>i when operator–>( ) returns this pointer:
Example
• #include <iostream> using int main()
namespace std; class {
myclass { myclass ob;
• public: ob->i = 10;
• int i; // same as ob.i
• myclass *operator->() cout << ob.i << " " << ob->i;
• { return 0;
• return this; }
• }
• }; Output:
10 10
Type Conversions
• When constants and variables of different types are mixed in an
expression, C++ applies automatic type conversion to the operand
as per certain rules. Similarly, an assignment operator also causes
the automatic type conversion.
• The type conversions are automatic as long as the data types
involved are built-in types.

❑ What happens when they are user defined data types?


❑ What if one of the operands is an object and the other is built-in
type variable?
❑ What if they belong to two different classes?
Continued…
• Since the user-defined data types are designed by us to suit our
requirements, the compiler does not support automatic type
conversions for such data types.

• Three type of situations might arise in the data conversion


between uncompatible types:
➢ Conversion from basic type to class type
➢ Conversion from class type to basic type
➢ Conversion from class type to class type
Basic to Class Type
• In this type of conversion, the source type is basic type and the
destination type is class type, i.e. basic data type is converted into
the class type.

• The conversion from basic type to the class type can be


performed in two ways:

➢ Using constructor
➢ Using Operator Overloading
Example (Using Constructor)
// Program to convert basic type to class type using constructor
int main()
#include <iostream>
{
using namespace std;
int duration;
class Time { cout<<"Enter time duration in minutes";
int hrs, min; cin>>duration;
public: Time t1=duration;
t1.display();
Time (int);
return 0;
void display(); }
};
Time :: Time (int t)
{
During type conversion using the
cout<<"Basic Type to ==> Class Type Conversion..."<<endl;
constructor we can pass only one
hrs=t/60;
argument and we can do type
min=t%60; conversion at the type of
} initialization only.
void Time::display()
{ cout<<hrs<< ": Hours(s)" <<endl; cout<<min<< " Minutes" <<endl;
}
Using Operator Overloading
• Type conversion from basic to class type can also be done by
operator overloading.

• Assignment operator can be overloaded for this purpose.

• Previous example of Time class can be rewritten for type


conversion using operator overloading concept to overload the
assignment operator (=).
Example
// Program to convert from basic type to class type using operator overloading
#include<iostream>
using namespace std;
class Time {
int hrs, min;
public:
void display();
void operator=(int); // overloading function
};
void Time::display()
{
cout<<hrs<< ": Hour(s) "<<endl ; cout<<min<<": Minutes"<<endl ;
}
void Time::operator=(int t)
{
cout<<"Basic Type to ==> Class Type Conversion..."<<endl;
hrs=t/60;
min=t%60;
}
Continued

int main()
{
Time t1;
int duration;
cout<<"Enter time duration in minutes";
cin>>duration;
cout<<"object t1 overloaded assignment..."<<endl;
t1=duration; //or, t1.operator=(duration);
t1.display();
return 0;
} By using overloaded
assignment operator we can
perform the type conversion at
any place in program.
Class to Basic Type
• In this type of conversion the source type is class type and the
destination type is basic type, i.e. class data type is converted into
the basic type.
• The constructor functions do not support this operation.
• It requires special casting operator function.
• The syntax for an overloaded casting operator function, usually
referred to as a conversion function, is:

operator typename( )
{
//Function statements
}
Continued…
• The conversion function should satisfy the following condition:

➢ It must be a class member.


➢ It must not specify the return value.
➢ It must not have any argument.
Example
#include<iostream>
using namespace std;
class Time
{
int hrs, min;
public:
Time (int ,int); // constructor
operator int(); // casting operator function
~Time() // destructor
{
cout<<"Destructor called..."<<endl;
}
};
Time::Time (int a,int b)
{
cout<<"Constructor called with two parameters..."<<endl;
hrs=a;
min=b;
}
Continued…
Time :: operator int()
{
cout<<"Class Type to Basic Type Conversion..."<<endl;
return(hrs*60+min);
}
int main()
{
int h, m, duration;
cout<<"Enter Hours ";
cin>>h; cout<<"Enter Minutes ";
cin>>m;
Time t(h,m); // construct object
duration = t; // casting conversion OR duration = (int)t
cout<<"Total Minutes are "<<duration;
cout<<"2nd method operator overloading "<<endl;
duration = t.operator int();
cout<<"Total Minutes are "<<duration;
return 0;
}
Class to Class Type
• In this type of conversion both the type that is source type and
the destination type are of class type.

• Conversion from one class to another class can be performed


either by using the constructor or type conversion function.
Example
//Program to convert class Time to another class Minute
#include<iostream> int getMinutes()
using namespace std; {
class Time int tot_min = ( hrs * 60 ) + min ;
return tot_min;
{
}
int hrs, min;
public: void display()
Time(int h,int m) {
{ cout<<"Hours: "<<hrs<<endl ;
cout<<" Minutes : "<<min <<endl ;
hrs=h;
}
min=m; };
}
Time()
{
cout<<"\n Time's Object Created";
}
Continued…
class Minute int main()
{ {
int min; Time t1(2,30);
public: t1.display();
Minute m1;
Minute()
m1.display();
{ m1 = t1; // conversion from Time to Minute
min = 0; t1.display();
} m1.display();
void operator=(Time T) return 0;
}
{
min=T.getMinutes();
}
void display()
{
cout<<"\n Total Minutes : " <<min<<endl;
}
};
Continued…
int main()
{
Time t1(2,30);
t1.display();
Minute m1;
m1.display();
m1 = t1; // conversion from Time to Minute
t1.display();
m1.display();
return 0;
}
Type Conversions Summary

Conversion Conversion takes place in


required Source Class Destination Class
Basic to Class Not Applicable Constructor

Class to Basic Casting Operator Not Applicable

Class to Class Casting Operator Constructor


Thanks
C++ Slides
Templates: Need of template, Function templates, Function
template with non-type parameter, Overloading function
templates, Class templates, Class template with non-type
parameter.
Need of template - motivation
• To reduce code duplication when supporting numerous data types

• int MyMax(int x, int y){ return x>y?x:y; }


• float MyMax(float x, float y){ return x>y?x:y; }
• char MyMax(char x, char y){ return x>y?x:y; }

• T MyMax(T x, T y){ return x>y?x:y;}


We can write a generic code for We can write a generic code for a
a function e.g. add() for class, to manipulate group of
integers, double, float etc. member variables & functions e.g.
linked list of strings, integers etc.
How to use template – an example
#include <iostream>
using namespace std;
template <class T>
T myMax(T x, T y){ return x>y?x:y;}
int main(){
cout<<myMax(10,20)<<endl;
cout<<myMax('a','z')<<endl;
cout<<myMax(-2.5,7.7)<<endl;
}
Function Templates(Generics) - definition
• We write a generic function that can be used for different
data types. Syntax of an example function -

template <class T>


T myMax(T x, T y){ return x>y?x:y;}

• Other examples could be sort(), max(), min(), printArray(),


show() etc.
Exercise – Make the generic template of -

void bubbleSort(int a[], int n) {


for (int i = 0; i < n - 1; i++)
for (int j = n - 1; i < j; j--)
if (a[j] < a[j - 1])
swap(a[j], a[j - 1]);
}
Answer:
template <class T>
void bubbleSort(T a[], int n) {
for (int i = 0; i < n - 1; i++)
for (int j = n - 1; i < j; j--)
if (a[j] < a[j - 1])
swap(a[j], a[j - 1]);
}
Exercise - Write a template for
int main(){
show(100,"hello hello");
show('k',1500);
show(1.23,2987);
}
Answer:
template <class T1, class T2>
void show(T1 a, T2 b){
cout<<a<<“, “<<b<<endl;
}
Function template with non-type parameter
• Non-type parameter is not a type (datatype) but a
value e.g. 100
• They are used to initialize a class or to specify the sizes
of class members

• template <class T, int size> // size is the non-type parameter


Function template with non-type parameter
#include<iostream>
using namespace std;
template <class T, int size>
void show(T a){cout<<a<<", "<<size;}
int main(){
show <char,10> ('c');
}
Overloading function templates
template <class T1, class T2>
void show(T1 a, T2 b){cout<<a<<", "<<b<<endl;}
void show(int a, int b){cout<<”For integer cases";}
int main(){
show(100,"hello hello");
show(3,3);
}
// Template class example
template <class T>
class Test {
T var;
public:
Test (T i) {var=i;}
T divideBy2 () {return var/2;}
};
int main(){
Test <int> t1(50);
Test <double> t2(-10.20);
cout<<t1.divideBy2()<<" "<<t2.divideBy2()<<endl;
}
Defining function outside the template class -
complicated
template <class T>
class Test {
T var;
public:
Test (T i) {var=i;}
T divideBy2 ();
};
template <class T>
T Test<T> :: divideBy2(){return var/2;} // complicated
// Class template with non-type parameter
template <class T, int n>
class Test {
T var;
public:
Test () {var = n; cout<<"n = "<<n<<endl;}
T divideBy2 () {return var/2;}
};
int main(){
Test <int,10> t1;
Test <double,20> t2;
cout<<t1.divideBy2()<<" "<<t2.divideBy2()<<endl;
}
Output
n = 10
n = 20
5 10
C++ slides - 8
Exception Handling: Exception handling mechanism, Multiple
Catch Blocks, Catch All exceptions, Throw an exception,
Exception Specification.
Exception handling definition & motivation
• Exception is a run-time error, such as divide by zero, array
out of bounds, file not found etc.

• It helps to continue the normal flow of the application even


in the case of runtime errors

• It makes the code simpler, cleaner, and less likely to miss


errors
if-else vs. exception handling
Only using errno & if-statements can make the error handling
intertwine with normal code to result a spaghetti
Try-catch organizes the code
try{
fun1();
fun2();
fun3();
} catch(error){
// … do something if error happens in any of the functions
}
// if any of the fun() is a constructor then you have to use if-else in the
constructor to handle the error since it cannot return anything, which
is not neat practice.
Exception thrown and caught
• Exception is thrown at runtime.
• If an exception is not handled (caught), it prints exception
message and terminates the program.
• Programmer’s job is to handle possible exceptions using try,
throw and catch to avoid abnormal program termination
Syntax of exception handling
try {
//some code
throw exception;
}
catch(type arg) {
//some code
}
Exception handling mechanism
// Without exception handling

float division(int x, int y){


return (x/y);
}
int main(){
int i=50, j=0;
float k=0;
k=division(i,j);
cout<<k<<endl;
}
Output
• Floating point exception (core dumped)
// With try, throw & catch
float division(int x, int y) {
if( y == 0 ) throw “Custom msg - divide by zero!";
return (x/y);
}
int main () {
int i = 25,j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
} catch (const char* e) { cout<< e << endl;}
}
Output
Custom msg - divide by zero!
// What will be the output?
float division(int x, int y) {
if( y == 0 ) throw 5;
return (x/y);
}
int main () {
float k = 0;
try {
k = division(25, k);
cout << k << endl;
}
catch (const char* e) { cout<< e << endl;}
catch(int i) {cout<<"caught i = "<<i<<endl;}
}
Output
caught i = 5
Multiple catch is possible
try {
//some code
throw exception;
}
catch(specific type exception) {//some code }

catch(generic type exception) { //some code }

Catch blocks must be ordered so that most specific exceptions get


caught before generic exceptions.
// Catch all exceptions – catch(…)

int main() {
try {
throw 10;
}
catch (char *e) { cout << "Caught " << e; }
catch (...) { cout << "Default Exception\n"; }
return 0;
}
Output
Default Exception
// What will be the output?

int main() {
try {
throw "10";
}
catch (const char *e) { cout << "Caught " << e; }
catch (...) { cout << "Default Exception\n"; }

}
Output
Caught 10
Exception Specification
• C++ provides a mechanism to ensure that a given function is
limited to throw only a specified list of exceptions.

void translate() throw(unknown_word,bad_grammar) {


/* ... */
}
• It will not throw any exception other than unknown _word or
bad_grammar
class unknown_word{};
class bad_grammar{};
void translate(int a) throw(unknown_word,bad_grammar) {
if (a==0) throw unknown_word();
else if(a==1) throw bad_grammar();
else throw 10;
}
int main(){
try{ translate(22);}
catch(unknown_word u){cout<<" unknown word";}
catch(bad_grammar g){cout<<" bad grammar";}
catch(...) {cout<<"Default catch";}
}
Output
terminate called after throwing an instance of 'int'

Aborted (core dumped)


C++ slides - 9
Standard Template Library: Fundamental idea about string,
iterators, hashes and other types, The String and Vector
classes vs C-style pointers
Standard Template Library (STL)
• STL provide general-purpose classes & functions to
implement commonly used algorithms and data structures
like vectors, lists, queues, and stacks.
STL has 3 components

• Containers – are the objects to organise/store various types


of data such as vector, list

• Algorithms – process data in containers e.g. sort()

• Iterator – generalised concept of pointers to point an


element in a container e.g. forward, bidirectional etc.
Algorithms use iterators to interact with containers
C++ string (as an
STL) vs char array

• A string is an
inbuilt C++ class
that contains a
char array but
automatically
manages it using
built in functions
Basic string program
#include <string>
#include<iostream>
using namespace std;
int main(){
string greeting ="Hello";
cout<<greeting;
}
String concatenation using ‘+’

string firstName = "John";

string lastName = "Doe";

string fullName = firstName + " " + lastName;


Some basic string functions
string txt = ”aBcDeF";

cout << txt.length();

cout<< txt[0]; //for the first letter


Some basic string functions
getline(cin,txt); //for including blank spaces

txt.substr(1, 3); // substring BcD (from 1 till 3 char)

str1.compare(str2); // compare string str1 with str2


Hashing for faster access & efficient storage
• Hashing maps given value to a particular key. This helps in
faster access.

• Let H(x) maps the value at key x%10 in an Array. Then


values {11,12,13,14,15} will be stored at {1,2,3,4,5} keys.

• Hashing is one way encryption which means you cannot go


from key to value. (1 to 11 for example)
Header file for hashing programs
• To run the following hash programs, you need #include<bits/stdc++>

• DevCpp may not have this file so either you can download and
include it using #include”bits/stdc++”

• OR use an online compiler


https://www.onlinegdb.com/online_c++_compiler
// Character hashing

#include<iostream>
using namespace std;
int main(){
hash <char> hash_character; //syntax for char type
cout << "Hash key is: " << hash_character(‘a’);
}
Output
Hash key is: 97

Looks like hash key is getting calculated same as ASCII value of


the character (for char case)
// Integer hashing

#include<iostream>
using namespace std;
int main(){
hash <int> hash_int;
cout << "Hash key is: " << hash_int(597)<<endl;
cout << "Hash key is: " << hash_int(-597)<<endl;
}
Output
Hash key is: 597
Hash key is: 18446744073709551019

Looks like hash key for positive integer is same as its value and
for negative it is a complicated code (may be t’s compliment,
not sure)
// String hashing

#include<iostream>
using namespace std;
int main(){
hash <string> hash_string;
cout << "Hash key is: " << hash_string("a")<<endl;
cout << "Hash key is: " << hash_string("apple")<<endl;
}
Output
Hash key is: 4993892634952068459

Hash key is: 13776597747624572848

For both “a” and “apple” the hash values are complicated
codes calculated internally.
Vector (another STL)
• Vector is a dynamic array with a size flexibility and direct
access to any element.
// Simple vector to insert int
values
#include<vector>
#include<iostream>
using namespace std;
int main() {
vector<int> v1;
v1.push_back(11);
v1.push_back(22);
vector<int>::iterator i;
for(i=v1.begin();i!=v1.end();++i)
cout << *i << endl;
}
Output
11
22
#include<algorithm> for vector functions
By including algorithm header file, many inbuilt
functions can be executed on vector such as:

• sort (values.begin(), values.end());


• reverse (values.begin(), values.end());
• random_shuffle (values.begin(), values.end());
• count (values.begin(), values.end(), 0); //count zeros
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
vector<int> v1;
v1.push_back(11); v1.push_back(33); v1.push_back(22);
sort (v1.begin(), v1.end());
vector<int>::iterator i;
for(i=v1.begin();i!=v1.end();++i)
cout<<*i<<endl;
cout<< “Max = “<<*max_element (v1.begin(), v1.end());
}
Output
11
22
33
Max = 33
String and Vector classes vs C-style pointers
(1) String constant of C++
In C++ one must use const for int
const char* str = ”This is a const string in C++";

Otherwise warning message -

main.cpp: In function ‘int main()’: main.cpp:4:13: warning: ISO


C++ forbids converting a string constant to ‘char*’ [-Wwrite-
strings] char* str = "This is a const string in C++";
(2) Cannot modify a string
int main() {
char* str = "Hello";
//warning – it should be const char *
str[1] = 'o';
}

Output - Segmentation fault


Using char[] modification is possible
int main() {
char str[] = "Hello";
str[1] = 'o';
cout << str << endl;
}
// Output will be Hollo
(3) char* is faster
• string will likely have more overhead

You might also like