SlideShare a Scribd company logo
OOP/AKN/Part_I/1
Object Oriented Programming
using C++
Module I
Ajit K Nayak, Ph.D.
SOA University, Odisha, India
OOP/AKN/Part_I/2
Contents
1. Fundamentals
2. Simple Program
3. Operators
4. Datatypes
5. Namespace
6. Function Prototypes
7. References
8. Passing Default Arguments
9. Function Overloading
10. Inline Functions
1. Named constants
2. Dynamic memory allocations
OOP/AKN/Part_I/3
Motivation
 OOD is the current technology for software
design and development.
 C++ is a tool to develop programs/codes for
OOP.
 Therefore, this subject is the bread and
butter for all those are interested in Software
Industry.
OOP/AKN/Part_I/4
About the Course
Two Goals for this course(OO-P)
Understand OO
 Thinking in Objects
Familiar with P
 Programming in C++
OOP/AKN/Part_I/5
Course Description
In this course:
C++ is used for illustrating and
implementing Object Oriented concepts.
OOP/AKN/Part_I/6
A Sample Program
/*Author : Ajit K Nayak
Reg #:
Date:
Source file: helo.cpp
Desc: A Simple Hello, World Program
*/
#include <iostream>
using namespace std;
main() {
/* the output statement */
cout << “Hello, World!”<<endl;
}
OOP/AKN/Part_I/7
How to Write and Execute in Linux
Open a file in vi / gedit with extension as
.cpp or .cxx or .C
Write the source code
Save and exit
Compile with c++ <filename> (or g++)
Check for errors
Execute with ./a.out
Guideline:- Do write the source code in well
indented format
OOP/AKN/Part_I/8
History of C and C++
C (K & R-70s) was evolved from BCPL(M.
Richards-67) and B(K. Thompson-70).
C++ is developed by Bjarne Stroustrup in
1980
C++ is an extension to C
latest standard C++11 ISO/IEC 14882:2011
Along with C-style programming it provides
capabilities for OOP
OOP/AKN/Part_I/9
The Creator
http://www.research.att.com/~bs/homepage.html
Bjarne
Stroustrup
OOP/AKN/Part_I/10
Guidelines
…B.Stroustrup
 Knowing C is not a prerequisite to learn C++
 The better one Knows C, the harder it seems to be to
avoid writing C++ in C-style.
Suggestions for C Programmers
 Macros are almost never necessary
 Don't Declare a variable before you need it
 Don‟t use malloc(), use new operator
 Try to avoid Void*, pointer arithmetic, unions and casts
 Try thinking a program as a set of interacting agents
represented as classes and objects
 …
OOP/AKN/Part_I/11
Prerequisite
It is expected that you know:
 branching: if – else, switch-case.
 Loop: for, while, do- while.
 Array, pointer, structure, function
etc.
 Not confident!!! Rush, pickup a C book
learn and write programs on above
topics.
OOP/AKN/Part_I/12
A Sample Program
/*Author : Ajit K Nayak
Reg #:
Date:
Source file: helo.cpp
Desc: A Simple Hello, World Program
*/
#include <iostream>
using namespace std;
main() {
//the output statement
cout << “Hello, World!”<<endl;
}
OOP/AKN/Part_I/13
Basic Operators- I
 Arithmetic operators ( +, -, *, /, % )
 x = 5 % 2.5
 Increment and decrement (++, --)
 x = 3++;
 Relational and comparison operators ( ==, !=, >, <, >=, <= ) x
= 5 > 3;
 Logical operators ( !, &&, || )
 Bitwise operators ( &, |, ^, ~, <<, >> )
 x = 5 & 3
 Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=,
|=)
 x = 3 * = 2
OOP/AKN/Part_I/14
Basic Operators- II
 Conditional ternary operator ( :? )
 x = 7== 5 ? 4 : 3 ;
 Comma operator ( , )
 a = (b=3, b+2);
 Explicit type casting operator
 int i; float f = 3.14; i = (int) f;
 Sizeof()
 x = sizeof (char);
 Precedence of Operators
 x = 5 + 7 % 2;
OOP/AKN/Part_I/15
Operators specific to C++
Stream insertion (<<)
Stream extraction (>>)
Dynamic memory allocation: new, new[ ]
Memory de-allocation: delete, delete[ ]
Scope resolution (::)
OOP/AKN/Part_I/16
Datatypes …A review
C++ has a set of fundamental types
 Boolean type (bool)
 Character type (char)
 Integer type (int)
 Floating point type (float)
 Double precision type (double)
In addition a user can define
 Enumeration type (enum)
to represent specific set of values
OOP/AKN/Part_I/17
Data types (contd.)
There also is
A type void used to signify the absence of data
From these above types we can construct
Pointer type (*)
Array type ([ ])
Reference type (&)
Finally the most powerful user-defined types
Data structures and classes(struct, class)
OOP/AKN/Part_I/18
A Classification
Boolean, character, and integer types are
collectively called as integral types
 Floating point types are called arithmetic
types
 Pointer, reference, and array are called
associated/derived types
 All of the above are built-in types
 Enumerations, structures, and classes are
called user defined types
OOP/AKN/Part_I/19
Boolean Type
A bool can have one of the two values;
true or false
It is used to express the results of logical
expressions
Example:
bool b1=a==b;
b1=true ->if a and b are of same value
= false -> otherwise
bool greater(int a, int b){ return a>b; }
 True has the value 1 and false has 0
OOP/AKN/Part_I/20
Boolean Type(contd)
Nonzero integers convert to true and 0 to
false
More Examples
bool b = 7; // b is true
int i = true // i=1
bool x = a+b // true if ….
bool y = a|b // true if a or b is true
if (b) // if b is true
What is the size required to store a certain type?
OOP/AKN/Part_I/21
Example program
int main(){
cout << "char: " << sizeof(char) << endl;
cout << "short: " << sizeof(short) << endl;
cout << "int: " << sizeof(int) << endl;
cout << "unsigned int: " << sizeof(unsigned int) << endl;
cout << "long int: " << sizeof(long int) << endl;
cout << "unsigned long int: " <<sizeof(unsigned long int)<< endl;
cout << "float: ” << sizeof(float)<<endl;
cout << "double: " << sizeof(double) << endl;
cout << "long double: " << sizeof(long double) << endl;
cout << "bool: " << sizeof(bool) << endl;
}
OOP/AKN/Part_I/22
Namespace
What is scope of a variable?
Outer
Block
{
int x=10;
…
{
int x=20;
…
}
…
}
Inner
Block
How to access
outer’s x and
Inner’s x?
If I can name the
blocks!
OOP/AKN/Part_I/23
Namespace contd.
 C++ namespaces can be used to group names
together. (give a name to a block)
 It provides a mechanism for expressing logical
grouping.
 If some declarations logically belong together
according to some criteria, they may be put in a
common namespace
 To use a namespace member, the member name
must be qualified with a namespace name and
the binary scope resolution operator
(namespace_name::member)
OOP/AKN/Part_I/24
Namespace contd.
namespace outer{
int x=10;
namespace inner{
int x=20;
}
}
Scope resolution Operator
If there is a global variable???
main(){
int x=0;
cout<<“self "<<x;
cout<<"Out "<<outer::x;
cout<<"In "<<outer::inner::x;
}
OOP/AKN/Part_I/25
Namespace Contd.
namespace mySpace{
int x=20;
int y=30,
int z=40;
}
To use these variables!
cout<< mySpace::x;
cout<< mySpace::y;
cout<< mySpace::z;
Another Way
using namespace mySpace;
cout<<x;
cout << y;
cout << z;
Note: cout and cin objects are
declared in predefined namespace
„std‟
Either write
using namespace std; or
std:: cout, std::cin etc.
OOP/AKN/Part_I/26
Function Prototype
main(){
int x = 5;
float y = 10.65;
doTask(x, y);
} //end of main
void doTask(int a, float b){
cout <<a+b<<„n‟ ;
}//end of function
void doTask(int a, float b);
Syntax:
• return_type
<function_name>(data type
of input parameter list
separated by comma );
• It can be called as function
declaration
• It is used at the time of
compilation to check if the
return value is handled
correctly and correct number
and type of arguments are
passed to the function
• Never use a function without a prototype
OOP/AKN/Part_I/27
Call By Value
#include <iostream>
using namespace std;
void increment(int);
main()
{
int i=2;
increment(i);
cout << “i = “ << i;
}
void increment(int x) { x++; }
OUTPUT ?
Explain!
OOP/AKN/Part_I/28
References
It is an alternative name for an object
It is used to specify arguments and return
values for functions in general and for
overloaded operators
Example
int i=1;
int& ir=i;
int x=ir;
ir=2;
//ir and i now refers to same value
// x=1
// i = 2
OOP/AKN/Part_I/29
References(contd.)
To ensure that a reference is a name for
something( bound to an object), we must
initialize the reference
Example:
int i=1;
int& r2;
Int& r1=i
//Error: initialization missing
//OK: r1 is now an alias for i
OOP/AKN/Part_I/30
Pointers and References
int ii = 0;
int& rr=ii;
rr++;
int *pp=&rr // or &ii
0
ii:
&ii
pp:
rr:
• pp is a variable which stores address of another variable
• rr is an alternative name (alias) for an existing variable
• The value of a reference cant be changed after initialization.
It always refers to the same object it was initialized. Which is
not the case in pointers
OOP/AKN/Part_I/31
Call By Reference
#include <iostream>
using namespace std;
void increment(int &);
main(){
int i=2;
increment(i);
cout << “i =“ << i;
}
void increment(int& x) {
x++;
}
OOP/AKN/Part_I/32
Example2
#include <iostream>
using namespace std;
int max(int&, int&);
main(){
int i=2,j=3;
cout<<max(i,j);
}
int max(int& x, int& y){
return x>y ? x:y;
}
Output?
OOP/AKN/Part_I/33
Example3
#include <iostream>
using namespace std;
int& max(int&, int&);
main(){
int i=2,j=3;
int &p=max(i,j);cout<<p; p=-30;
cout<<“i=“<i<„t‟<<“j=“<<j<<„t‟<<“p=“<<p
<<endl;
}
int& max(int &x, int &y){
return x>y ? x:y;
}
Output?
OOP/AKN/Part_I/34
References contd.
 Calls to functions that returns reference can be
put on the left side of the assignment operator.
main(){
int i=2,j=3;
max(i,j)= -30;
cout<<“i=“<i<„t‟<<“j=“<<j<<„t‟<<endl;
}
 The value –30 will be assigned to the larger of
i & j
OOP/AKN/Part_I/35
Use of passing by reference
To manipulate original values of variables
inside a function
To pass large objects
To return more than one value from a
function (virtually)
To use a function to the left side of =
operator
Any other, you may suggest!
OOP/AKN/Part_I/36
Default Arguments
Parameters can be assigned default values.
Parameters assume their default values
when no actual parameters are specified for
them in a function call.
 A default argument is type checked at the
time of function declaration and evaluated at
the time of call
 Default arguments may be provided for
trailing arguments only
OOP/AKN/Part_I/37
Example
// Find the sum of numbers in a range of values
// Between “lower” and “upper” using increment “inc”
int sum(int lower,int upper=100,int inc=1){
int sum=0;
for(int k=lower; k<=upper; k+= inc)
sum += k;
return sum;
}
main(){
cout<<sum(1);
cout<<sum(1, 10);
cout<<sum(1, 10, 2);
}
Design a default argument function with its prototype!
//5050
//55
//25
Write the prototype for sum!!!
OOP/AKN/Part_I/38
Function Overloading
A function is said to be overloaded when the same
function name is used for different purposes.
It allows you to use the same name for
different functions
void print(char);
void print(float);
Thus to overload a function we require to pass
different types of arguments to each function
with same name.
OOP/AKN/Part_I/39
Function Overloading(contd)
 Compiler decides the function to be invoked using a
series of criteria in order
1. Exact match i.e. vol(5); int vol(int)
2. Match using integral promotions i.e. char to int, float to
double etc.
3. Match using standard conversions i.e. int to double,
double to long double
4. Match using user-defined conversions i.e. conversion
between user-defined types
5. Match using the ellipsis (…) i.e unspecified number of
arguments
OOP/AKN/Part_I/40
Function Overloading(contd)
If more than one match is found, the call is rejected
by the compiler as ambiguous
Example
void print(int);
void print(const char*);
void print(double);
void print(long);
void print(char);
OOP/AKN/Part_I/41
Function Overloading(contd)
void h(char c, int i, short s,float
f){
print(c);
print(i);
print(s);
print(f);
print(„a‟);
print(49);
print(0);
print(“a”);
}
// Exact match: print(char)
// Exact match: print(int)
// integral promotion:print(int)
// integral :print(double)
// Exact match: print(char)
// Exact match: print(int)
// Exact match: print(int)
// Exact :print(const char*)
OOP/AKN/Part_I/42
Function Overloading(contd)
 Overloading solely on return value is not allowed in
C++
i.e. you cannot write
void f();
int f();
Task
Overload a function add( arg1, arg2) s.t. when both are
integers and doubles it produces the addition result,
when both are strings it produces another string by
concatenating both .
OOP/AKN/Part_I/43
Inline Functions
Every time a function is called, it takes a lot of
extra time due to
 Jumping to function
 Saving registers
 Returning to calling function etc.
When a function is small, it becomes an
overhead
 One solution is to use macros
#define max(a,b) ((a) > (b) ? (a):(b));
OOP/AKN/Part_I/44
Inline functions (contd.)
But macros has various disadvantages(?)
An alternative in C++ is to use inline
functions:
inline int max(int a, int b) {
return (a > b ? a : b);
}
An Inline function is a function that is
expanded in line when invoked.
The compiler inserts the equivalent function
code at the place of invocation
OOP/AKN/Part_I/45
Macro vs Inline function
#define square(x) x*x
main(){
cout<<square(3+2);
int y=3;
cout<<square(++y);
}
• Both fails, as macro is a blind replacement of
statements.
• Unlike macros, inline functions may be declared
any where in the program
OOP/AKN/Part_I/46
Named Constants
Only one method in C:
#define ArraySize 100;
//Macro constants
Another way in C++:
 const ArraySize =100;
Again in C++:
 constant can be used in local scope
 const is often used when the value cannot
be changed
OOP/AKN/Part_I/47
Examples of Using const
 const int count = 5;
 static const float average = 0.5;
 const float f; //error!, invalid!
 extern const float f; //ok, extern linkage
 const int c3=myFunc(3); //ok, don‟t know the
//value at compile time
 const int* p=&c2; //need to allocate space for c2
 void (const int* p) { //cant modify *p here }
 const int myFunc(int) // ok, but no use
OOP/AKN/Part_I/48
Dynamic Memory Allocation
In C we write (for a single value)
int* ip;
ip = (int*)malloc(sizeof(int) );
…
free (ip);
In C++ we will write
int* ip;
ip = new int;
...
delete ip;
OOP/AKN/Part_I/49
Dynamic Memory Allocation
In C we write (for multiple values)
int* ip;
ip = (int*)malloc(sizeof(int) * 100);
…
free ip;
In C++ we will write
int* ip;
ip = new int[100];
...
delete [ ] ip;
OOP/AKN/Part_I/50
New/Delete opearators
int* p=new int; delete p;
int* p=new int(25);delete p;
int* p=new int[25];delete []p;
Task
Find a method to declare a multi-dimensional
array using new operator
OOP/AKN/Part_I/51
Memory Leak
 Memory leak:
 when you do not free a block of memory allocated with
the new operator
 or when you make it impossible to do so.
 As a consequence your application may
eventually run out of memory and may even
cause the system to crash.
void func(){
char *ch;
ch = new char[100];
}
OOP/AKN/Part_I/52
Dangling Pointer
 Dangling pointer points to memory that has
already been freed. The storage is no longer
allocated. Trying to access it might cause a
Segmentation fault.
1. char* func() {
char str[10];
strcpy(str,"Hello!");
return(str);
}
2. int *c = new int; delete c;
*c = 3;
OOP/AKN/Part_I/53
Readings
Programming
 Bjarne Stroustrup, The C++ Programming Language, PE
 Lippman, Lajoie, C++ Primer, Addison-Wesley
 B. Eckel, Thinking in C++, Vol I and Vol II
 Deitel & Deitel, C++ How to program
 Schildt, C++ The complete reference
 S. Sahay, OOP with C++
 E. Balagurusami, Object oriented programming with C++
Concepts
 G.Booch, Object Oriented Analysis & Design
 Bertand Meyer, Object Oriented Software Construction

More Related Content

What's hot (17)

PPTX
Object Oriented Technologies
Tushar B Kute
 
PDF
C++ [ principles of object oriented programming ]
Rome468
 
PPTX
Oop in c++ lecture 1
zk75977
 
PDF
Object oriented concepts
Pranali Chaudhari
 
PDF
C# Summer course - Lecture 2
mohamedsamyali
 
PPTX
Object-oriented programming
Neelesh Shukla
 
PPT
C++ classes
imhammadali
 
PPT
Object Oriented Technologies
Umesh Nikam
 
PPT
Inheritance : Extending Classes
Nilesh Dalvi
 
PPT
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Eduardo Bergavera
 
PPTX
Object oriented programming in C++
jehan1987
 
PPT
Polymorphism
Nilesh Dalvi
 
PPT
Concepts In Object Oriented Programming Languages
ppd1961
 
PPTX
Programming Fundamentals With OOPs Concepts (Java Examples Based)
indiangarg
 
PDF
Inheritance
Pranali Chaudhari
 
PDF
Object-oriented Programming-with C#
Doncho Minkov
 
PPTX
Object Oriented Programming Concepts
Bhushan Nagaraj
 
Object Oriented Technologies
Tushar B Kute
 
C++ [ principles of object oriented programming ]
Rome468
 
Oop in c++ lecture 1
zk75977
 
Object oriented concepts
Pranali Chaudhari
 
C# Summer course - Lecture 2
mohamedsamyali
 
Object-oriented programming
Neelesh Shukla
 
C++ classes
imhammadali
 
Object Oriented Technologies
Umesh Nikam
 
Inheritance : Extending Classes
Nilesh Dalvi
 
Chapter1 - Introduction to Object-Oriented Programming and Software Development
Eduardo Bergavera
 
Object oriented programming in C++
jehan1987
 
Polymorphism
Nilesh Dalvi
 
Concepts In Object Oriented Programming Languages
ppd1961
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
indiangarg
 
Inheritance
Pranali Chaudhari
 
Object-oriented Programming-with C#
Doncho Minkov
 
Object Oriented Programming Concepts
Bhushan Nagaraj
 

Viewers also liked (20)

PPT
Uml Omg Fundamental Certification 2
Ricardo Quintero
 
PDF
Object Oriented Programming using C++ Part III
Ajit Nayak
 
PPTX
The Ultimate gift
Sebastien Juras
 
PPTX
The Bad Guy in your company and how have him under control
Sebastien Juras
 
PPT
03 administracion de requisitos
Ricardo Quintero
 
PPTX
The badguy summary
Sebastien Juras
 
PDF
Software Engineering an Introduction
Ajit Nayak
 
PPTX
Innovation is almost impossible for older companies
Sebastien Juras
 
PPTX
Psychology explains the power of Storytelling
Sebastien Juras
 
PDF
Software Engineering :Behavioral Modelling - I Sequence diagram
Ajit Nayak
 
PDF
Manual 02
Ricardo Quintero
 
PPT
Uml Omg Fundamental Certification 5
Ricardo Quintero
 
PPTX
Six things to know about your brain to become an expert
Sebastien Juras
 
PDF
Operating Systems Part III-Memory Management
Ajit Nayak
 
PPTX
One thing you can do to increase your charisma
Sebastien Juras
 
PPTX
Things to know to improve your willpower
Sebastien Juras
 
PDF
Object Oriented Analysis Design using UML
Ajit Nayak
 
PPTX
The Humming-bird’s share
Sebastien Juras
 
PDF
Computer Networks Module I
Ajit Nayak
 
PDF
Ns2: OTCL - PArt II
Ajit Nayak
 
Uml Omg Fundamental Certification 2
Ricardo Quintero
 
Object Oriented Programming using C++ Part III
Ajit Nayak
 
The Ultimate gift
Sebastien Juras
 
The Bad Guy in your company and how have him under control
Sebastien Juras
 
03 administracion de requisitos
Ricardo Quintero
 
The badguy summary
Sebastien Juras
 
Software Engineering an Introduction
Ajit Nayak
 
Innovation is almost impossible for older companies
Sebastien Juras
 
Psychology explains the power of Storytelling
Sebastien Juras
 
Software Engineering :Behavioral Modelling - I Sequence diagram
Ajit Nayak
 
Manual 02
Ricardo Quintero
 
Uml Omg Fundamental Certification 5
Ricardo Quintero
 
Six things to know about your brain to become an expert
Sebastien Juras
 
Operating Systems Part III-Memory Management
Ajit Nayak
 
One thing you can do to increase your charisma
Sebastien Juras
 
Things to know to improve your willpower
Sebastien Juras
 
Object Oriented Analysis Design using UML
Ajit Nayak
 
The Humming-bird’s share
Sebastien Juras
 
Computer Networks Module I
Ajit Nayak
 
Ns2: OTCL - PArt II
Ajit Nayak
 
Ad

Similar to Object Oriented Programming using C++ Part I (20)

PPTX
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
PPTX
Structured Languages
Mufaddal Nullwala
 
PPTX
C++ tutorial assignment - 23MTS5730.pptx
sp1312004
 
PPTX
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
crazysamarth927
 
PPT
lecture2 (1).ppt variable s and operators
ChittyAvula
 
PDF
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Akhil Mittal
 
PPTX
C++ Class & object pointer in c++ programming language
HariTharshiniBscIT1
 
PDF
Object Oriented Programming notes provided
dummydoona
 
PPT
C++ Interview Questions
Kaushik Raghupathi
 
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
PPTX
Presentation on topic of c and c++ programming language.(.pptx
panawarahul7
 
PPTX
Object Oriented Programming using C++: Ch06 Objects and Classes.pptx
RashidFaridChishti
 
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
PPTX
Presentation 5th
Connex
 
PPTX
PRINCE PRESENTATION(1).pptx
SajalKesharwani2
 
PPT
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
PPT
C++ Programming Course
Dennis Chang
 
PPTX
Chapter 2 part II array and structure.pptx
abenezertekalign118
 
PDF
C++ Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
PDF
C++ questions And Answer
lavparmar007
 
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
Structured Languages
Mufaddal Nullwala
 
C++ tutorial assignment - 23MTS5730.pptx
sp1312004
 
UNIT - 1- Ood ddnwkjfnewcsdkjnjkfnskfn.pptx
crazysamarth927
 
lecture2 (1).ppt variable s and operators
ChittyAvula
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Akhil Mittal
 
C++ Class & object pointer in c++ programming language
HariTharshiniBscIT1
 
Object Oriented Programming notes provided
dummydoona
 
C++ Interview Questions
Kaushik Raghupathi
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
Presentation on topic of c and c++ programming language.(.pptx
panawarahul7
 
Object Oriented Programming using C++: Ch06 Objects and Classes.pptx
RashidFaridChishti
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
Presentation 5th
Connex
 
PRINCE PRESENTATION(1).pptx
SajalKesharwani2
 
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
C++ Programming Course
Dennis Chang
 
Chapter 2 part II array and structure.pptx
abenezertekalign118
 
C++ Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
C++ questions And Answer
lavparmar007
 
Ad

More from Ajit Nayak (20)

PDF
Software Engineering : Software testing
Ajit Nayak
 
PDF
Software Engineering :Behavioral Modelling - II State diagram
Ajit Nayak
 
PDF
Software Engineering :UML class diagrams
Ajit Nayak
 
PDF
Software Engineering : OOAD using UML
Ajit Nayak
 
PDF
Software Engineering : Requirement Analysis & Specification
Ajit Nayak
 
PDF
Software Engineering : Process Models
Ajit Nayak
 
PDF
Database Programming using SQL
Ajit Nayak
 
PDF
Ns2: Introduction - Part I
Ajit Nayak
 
PDF
NS2: AWK and GNUplot - PArt III
Ajit Nayak
 
PDF
Socket programming using C
Ajit Nayak
 
PDF
Parallel programming using MPI
Ajit Nayak
 
PDF
Operating Systems Part I-Basics
Ajit Nayak
 
PDF
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Ajit Nayak
 
PDF
Introduction to database-Transaction Concurrency and Recovery
Ajit Nayak
 
PDF
Introduction to database-Formal Query language and Relational calculus
Ajit Nayak
 
PDF
Introduction to database-Normalisation
Ajit Nayak
 
PDF
Introduction to database-ER Model
Ajit Nayak
 
PDF
Computer Networks Module III
Ajit Nayak
 
PDF
Computer Networks Module II
Ajit Nayak
 
PDF
Object Oriented Programming using C++ Part II
Ajit Nayak
 
Software Engineering : Software testing
Ajit Nayak
 
Software Engineering :Behavioral Modelling - II State diagram
Ajit Nayak
 
Software Engineering :UML class diagrams
Ajit Nayak
 
Software Engineering : OOAD using UML
Ajit Nayak
 
Software Engineering : Requirement Analysis & Specification
Ajit Nayak
 
Software Engineering : Process Models
Ajit Nayak
 
Database Programming using SQL
Ajit Nayak
 
Ns2: Introduction - Part I
Ajit Nayak
 
NS2: AWK and GNUplot - PArt III
Ajit Nayak
 
Socket programming using C
Ajit Nayak
 
Parallel programming using MPI
Ajit Nayak
 
Operating Systems Part I-Basics
Ajit Nayak
 
Operating Systems Part II-Process Scheduling, Synchronisation & Deadlock
Ajit Nayak
 
Introduction to database-Transaction Concurrency and Recovery
Ajit Nayak
 
Introduction to database-Formal Query language and Relational calculus
Ajit Nayak
 
Introduction to database-Normalisation
Ajit Nayak
 
Introduction to database-ER Model
Ajit Nayak
 
Computer Networks Module III
Ajit Nayak
 
Computer Networks Module II
Ajit Nayak
 
Object Oriented Programming using C++ Part II
Ajit Nayak
 

Recently uploaded (20)

PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
MRRS Strength and Durability of Concrete
CivilMythili
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
Design Thinking basics for Engineers.pdf
CMR University
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 

Object Oriented Programming using C++ Part I

  • 1. OOP/AKN/Part_I/1 Object Oriented Programming using C++ Module I Ajit K Nayak, Ph.D. SOA University, Odisha, India
  • 2. OOP/AKN/Part_I/2 Contents 1. Fundamentals 2. Simple Program 3. Operators 4. Datatypes 5. Namespace 6. Function Prototypes 7. References 8. Passing Default Arguments 9. Function Overloading 10. Inline Functions 1. Named constants 2. Dynamic memory allocations
  • 3. OOP/AKN/Part_I/3 Motivation  OOD is the current technology for software design and development.  C++ is a tool to develop programs/codes for OOP.  Therefore, this subject is the bread and butter for all those are interested in Software Industry.
  • 4. OOP/AKN/Part_I/4 About the Course Two Goals for this course(OO-P) Understand OO  Thinking in Objects Familiar with P  Programming in C++
  • 5. OOP/AKN/Part_I/5 Course Description In this course: C++ is used for illustrating and implementing Object Oriented concepts.
  • 6. OOP/AKN/Part_I/6 A Sample Program /*Author : Ajit K Nayak Reg #: Date: Source file: helo.cpp Desc: A Simple Hello, World Program */ #include <iostream> using namespace std; main() { /* the output statement */ cout << “Hello, World!”<<endl; }
  • 7. OOP/AKN/Part_I/7 How to Write and Execute in Linux Open a file in vi / gedit with extension as .cpp or .cxx or .C Write the source code Save and exit Compile with c++ <filename> (or g++) Check for errors Execute with ./a.out Guideline:- Do write the source code in well indented format
  • 8. OOP/AKN/Part_I/8 History of C and C++ C (K & R-70s) was evolved from BCPL(M. Richards-67) and B(K. Thompson-70). C++ is developed by Bjarne Stroustrup in 1980 C++ is an extension to C latest standard C++11 ISO/IEC 14882:2011 Along with C-style programming it provides capabilities for OOP
  • 10. OOP/AKN/Part_I/10 Guidelines …B.Stroustrup  Knowing C is not a prerequisite to learn C++  The better one Knows C, the harder it seems to be to avoid writing C++ in C-style. Suggestions for C Programmers  Macros are almost never necessary  Don't Declare a variable before you need it  Don‟t use malloc(), use new operator  Try to avoid Void*, pointer arithmetic, unions and casts  Try thinking a program as a set of interacting agents represented as classes and objects  …
  • 11. OOP/AKN/Part_I/11 Prerequisite It is expected that you know:  branching: if – else, switch-case.  Loop: for, while, do- while.  Array, pointer, structure, function etc.  Not confident!!! Rush, pickup a C book learn and write programs on above topics.
  • 12. OOP/AKN/Part_I/12 A Sample Program /*Author : Ajit K Nayak Reg #: Date: Source file: helo.cpp Desc: A Simple Hello, World Program */ #include <iostream> using namespace std; main() { //the output statement cout << “Hello, World!”<<endl; }
  • 13. OOP/AKN/Part_I/13 Basic Operators- I  Arithmetic operators ( +, -, *, /, % )  x = 5 % 2.5  Increment and decrement (++, --)  x = 3++;  Relational and comparison operators ( ==, !=, >, <, >=, <= ) x = 5 > 3;  Logical operators ( !, &&, || )  Bitwise operators ( &, |, ^, ~, <<, >> )  x = 5 & 3  Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)  x = 3 * = 2
  • 14. OOP/AKN/Part_I/14 Basic Operators- II  Conditional ternary operator ( :? )  x = 7== 5 ? 4 : 3 ;  Comma operator ( , )  a = (b=3, b+2);  Explicit type casting operator  int i; float f = 3.14; i = (int) f;  Sizeof()  x = sizeof (char);  Precedence of Operators  x = 5 + 7 % 2;
  • 15. OOP/AKN/Part_I/15 Operators specific to C++ Stream insertion (<<) Stream extraction (>>) Dynamic memory allocation: new, new[ ] Memory de-allocation: delete, delete[ ] Scope resolution (::)
  • 16. OOP/AKN/Part_I/16 Datatypes …A review C++ has a set of fundamental types  Boolean type (bool)  Character type (char)  Integer type (int)  Floating point type (float)  Double precision type (double) In addition a user can define  Enumeration type (enum) to represent specific set of values
  • 17. OOP/AKN/Part_I/17 Data types (contd.) There also is A type void used to signify the absence of data From these above types we can construct Pointer type (*) Array type ([ ]) Reference type (&) Finally the most powerful user-defined types Data structures and classes(struct, class)
  • 18. OOP/AKN/Part_I/18 A Classification Boolean, character, and integer types are collectively called as integral types  Floating point types are called arithmetic types  Pointer, reference, and array are called associated/derived types  All of the above are built-in types  Enumerations, structures, and classes are called user defined types
  • 19. OOP/AKN/Part_I/19 Boolean Type A bool can have one of the two values; true or false It is used to express the results of logical expressions Example: bool b1=a==b; b1=true ->if a and b are of same value = false -> otherwise bool greater(int a, int b){ return a>b; }  True has the value 1 and false has 0
  • 20. OOP/AKN/Part_I/20 Boolean Type(contd) Nonzero integers convert to true and 0 to false More Examples bool b = 7; // b is true int i = true // i=1 bool x = a+b // true if …. bool y = a|b // true if a or b is true if (b) // if b is true What is the size required to store a certain type?
  • 21. OOP/AKN/Part_I/21 Example program int main(){ cout << "char: " << sizeof(char) << endl; cout << "short: " << sizeof(short) << endl; cout << "int: " << sizeof(int) << endl; cout << "unsigned int: " << sizeof(unsigned int) << endl; cout << "long int: " << sizeof(long int) << endl; cout << "unsigned long int: " <<sizeof(unsigned long int)<< endl; cout << "float: ” << sizeof(float)<<endl; cout << "double: " << sizeof(double) << endl; cout << "long double: " << sizeof(long double) << endl; cout << "bool: " << sizeof(bool) << endl; }
  • 22. OOP/AKN/Part_I/22 Namespace What is scope of a variable? Outer Block { int x=10; … { int x=20; … } … } Inner Block How to access outer’s x and Inner’s x? If I can name the blocks!
  • 23. OOP/AKN/Part_I/23 Namespace contd.  C++ namespaces can be used to group names together. (give a name to a block)  It provides a mechanism for expressing logical grouping.  If some declarations logically belong together according to some criteria, they may be put in a common namespace  To use a namespace member, the member name must be qualified with a namespace name and the binary scope resolution operator (namespace_name::member)
  • 24. OOP/AKN/Part_I/24 Namespace contd. namespace outer{ int x=10; namespace inner{ int x=20; } } Scope resolution Operator If there is a global variable??? main(){ int x=0; cout<<“self "<<x; cout<<"Out "<<outer::x; cout<<"In "<<outer::inner::x; }
  • 25. OOP/AKN/Part_I/25 Namespace Contd. namespace mySpace{ int x=20; int y=30, int z=40; } To use these variables! cout<< mySpace::x; cout<< mySpace::y; cout<< mySpace::z; Another Way using namespace mySpace; cout<<x; cout << y; cout << z; Note: cout and cin objects are declared in predefined namespace „std‟ Either write using namespace std; or std:: cout, std::cin etc.
  • 26. OOP/AKN/Part_I/26 Function Prototype main(){ int x = 5; float y = 10.65; doTask(x, y); } //end of main void doTask(int a, float b){ cout <<a+b<<„n‟ ; }//end of function void doTask(int a, float b); Syntax: • return_type <function_name>(data type of input parameter list separated by comma ); • It can be called as function declaration • It is used at the time of compilation to check if the return value is handled correctly and correct number and type of arguments are passed to the function • Never use a function without a prototype
  • 27. OOP/AKN/Part_I/27 Call By Value #include <iostream> using namespace std; void increment(int); main() { int i=2; increment(i); cout << “i = “ << i; } void increment(int x) { x++; } OUTPUT ? Explain!
  • 28. OOP/AKN/Part_I/28 References It is an alternative name for an object It is used to specify arguments and return values for functions in general and for overloaded operators Example int i=1; int& ir=i; int x=ir; ir=2; //ir and i now refers to same value // x=1 // i = 2
  • 29. OOP/AKN/Part_I/29 References(contd.) To ensure that a reference is a name for something( bound to an object), we must initialize the reference Example: int i=1; int& r2; Int& r1=i //Error: initialization missing //OK: r1 is now an alias for i
  • 30. OOP/AKN/Part_I/30 Pointers and References int ii = 0; int& rr=ii; rr++; int *pp=&rr // or &ii 0 ii: &ii pp: rr: • pp is a variable which stores address of another variable • rr is an alternative name (alias) for an existing variable • The value of a reference cant be changed after initialization. It always refers to the same object it was initialized. Which is not the case in pointers
  • 31. OOP/AKN/Part_I/31 Call By Reference #include <iostream> using namespace std; void increment(int &); main(){ int i=2; increment(i); cout << “i =“ << i; } void increment(int& x) { x++; }
  • 32. OOP/AKN/Part_I/32 Example2 #include <iostream> using namespace std; int max(int&, int&); main(){ int i=2,j=3; cout<<max(i,j); } int max(int& x, int& y){ return x>y ? x:y; } Output?
  • 33. OOP/AKN/Part_I/33 Example3 #include <iostream> using namespace std; int& max(int&, int&); main(){ int i=2,j=3; int &p=max(i,j);cout<<p; p=-30; cout<<“i=“<i<„t‟<<“j=“<<j<<„t‟<<“p=“<<p <<endl; } int& max(int &x, int &y){ return x>y ? x:y; } Output?
  • 34. OOP/AKN/Part_I/34 References contd.  Calls to functions that returns reference can be put on the left side of the assignment operator. main(){ int i=2,j=3; max(i,j)= -30; cout<<“i=“<i<„t‟<<“j=“<<j<<„t‟<<endl; }  The value –30 will be assigned to the larger of i & j
  • 35. OOP/AKN/Part_I/35 Use of passing by reference To manipulate original values of variables inside a function To pass large objects To return more than one value from a function (virtually) To use a function to the left side of = operator Any other, you may suggest!
  • 36. OOP/AKN/Part_I/36 Default Arguments Parameters can be assigned default values. Parameters assume their default values when no actual parameters are specified for them in a function call.  A default argument is type checked at the time of function declaration and evaluated at the time of call  Default arguments may be provided for trailing arguments only
  • 37. OOP/AKN/Part_I/37 Example // Find the sum of numbers in a range of values // Between “lower” and “upper” using increment “inc” int sum(int lower,int upper=100,int inc=1){ int sum=0; for(int k=lower; k<=upper; k+= inc) sum += k; return sum; } main(){ cout<<sum(1); cout<<sum(1, 10); cout<<sum(1, 10, 2); } Design a default argument function with its prototype! //5050 //55 //25 Write the prototype for sum!!!
  • 38. OOP/AKN/Part_I/38 Function Overloading A function is said to be overloaded when the same function name is used for different purposes. It allows you to use the same name for different functions void print(char); void print(float); Thus to overload a function we require to pass different types of arguments to each function with same name.
  • 39. OOP/AKN/Part_I/39 Function Overloading(contd)  Compiler decides the function to be invoked using a series of criteria in order 1. Exact match i.e. vol(5); int vol(int) 2. Match using integral promotions i.e. char to int, float to double etc. 3. Match using standard conversions i.e. int to double, double to long double 4. Match using user-defined conversions i.e. conversion between user-defined types 5. Match using the ellipsis (…) i.e unspecified number of arguments
  • 40. OOP/AKN/Part_I/40 Function Overloading(contd) If more than one match is found, the call is rejected by the compiler as ambiguous Example void print(int); void print(const char*); void print(double); void print(long); void print(char);
  • 41. OOP/AKN/Part_I/41 Function Overloading(contd) void h(char c, int i, short s,float f){ print(c); print(i); print(s); print(f); print(„a‟); print(49); print(0); print(“a”); } // Exact match: print(char) // Exact match: print(int) // integral promotion:print(int) // integral :print(double) // Exact match: print(char) // Exact match: print(int) // Exact match: print(int) // Exact :print(const char*)
  • 42. OOP/AKN/Part_I/42 Function Overloading(contd)  Overloading solely on return value is not allowed in C++ i.e. you cannot write void f(); int f(); Task Overload a function add( arg1, arg2) s.t. when both are integers and doubles it produces the addition result, when both are strings it produces another string by concatenating both .
  • 43. OOP/AKN/Part_I/43 Inline Functions Every time a function is called, it takes a lot of extra time due to  Jumping to function  Saving registers  Returning to calling function etc. When a function is small, it becomes an overhead  One solution is to use macros #define max(a,b) ((a) > (b) ? (a):(b));
  • 44. OOP/AKN/Part_I/44 Inline functions (contd.) But macros has various disadvantages(?) An alternative in C++ is to use inline functions: inline int max(int a, int b) { return (a > b ? a : b); } An Inline function is a function that is expanded in line when invoked. The compiler inserts the equivalent function code at the place of invocation
  • 45. OOP/AKN/Part_I/45 Macro vs Inline function #define square(x) x*x main(){ cout<<square(3+2); int y=3; cout<<square(++y); } • Both fails, as macro is a blind replacement of statements. • Unlike macros, inline functions may be declared any where in the program
  • 46. OOP/AKN/Part_I/46 Named Constants Only one method in C: #define ArraySize 100; //Macro constants Another way in C++:  const ArraySize =100; Again in C++:  constant can be used in local scope  const is often used when the value cannot be changed
  • 47. OOP/AKN/Part_I/47 Examples of Using const  const int count = 5;  static const float average = 0.5;  const float f; //error!, invalid!  extern const float f; //ok, extern linkage  const int c3=myFunc(3); //ok, don‟t know the //value at compile time  const int* p=&c2; //need to allocate space for c2  void (const int* p) { //cant modify *p here }  const int myFunc(int) // ok, but no use
  • 48. OOP/AKN/Part_I/48 Dynamic Memory Allocation In C we write (for a single value) int* ip; ip = (int*)malloc(sizeof(int) ); … free (ip); In C++ we will write int* ip; ip = new int; ... delete ip;
  • 49. OOP/AKN/Part_I/49 Dynamic Memory Allocation In C we write (for multiple values) int* ip; ip = (int*)malloc(sizeof(int) * 100); … free ip; In C++ we will write int* ip; ip = new int[100]; ... delete [ ] ip;
  • 50. OOP/AKN/Part_I/50 New/Delete opearators int* p=new int; delete p; int* p=new int(25);delete p; int* p=new int[25];delete []p; Task Find a method to declare a multi-dimensional array using new operator
  • 51. OOP/AKN/Part_I/51 Memory Leak  Memory leak:  when you do not free a block of memory allocated with the new operator  or when you make it impossible to do so.  As a consequence your application may eventually run out of memory and may even cause the system to crash. void func(){ char *ch; ch = new char[100]; }
  • 52. OOP/AKN/Part_I/52 Dangling Pointer  Dangling pointer points to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault. 1. char* func() { char str[10]; strcpy(str,"Hello!"); return(str); } 2. int *c = new int; delete c; *c = 3;
  • 53. OOP/AKN/Part_I/53 Readings Programming  Bjarne Stroustrup, The C++ Programming Language, PE  Lippman, Lajoie, C++ Primer, Addison-Wesley  B. Eckel, Thinking in C++, Vol I and Vol II  Deitel & Deitel, C++ How to program  Schildt, C++ The complete reference  S. Sahay, OOP with C++  E. Balagurusami, Object oriented programming with C++ Concepts  G.Booch, Object Oriented Analysis & Design  Bertand Meyer, Object Oriented Software Construction