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
Contents1. 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/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 reviewC++ 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 arithmetictypes
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 programint 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
NamespaceWhat 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:
&iipp:
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 ArgumentsParameters 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 OverloadingA 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 FunctionsEvery 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 writeint* 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 writeint* ip;
ip = new int[100];
...
delete [ ] ip;
OOP/AKN/Part_I/50
New/Delete opearatorsint* 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 LeakMemory 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
ReadingsProgramming 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