This document provides an introduction to object-oriented programming using C++. It outlines the topics that will be covered in the course, including fundamentals, simple programs, operators, data types, namespaces, function prototypes, references, default arguments, function overloading, and inline functions. It discusses the motivation for learning OOP and C++. The document also contains examples of simple C++ programs and explanations of concepts like function prototypes, call by value/reference, and overloading. The goal of the course is to understand object-oriented thinking and become familiar with programming in C++.
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.
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;
}
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?
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++;
}
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