You are on page 1of 38

Object Oriented Programming

through C++
Narendra V G
Dept. of CSE
MIT, Manipal
Preferred text:
Object-Oriented Programming with C++ by
Sourav Sahay
Object-Oriented Programming with C++ by
E Balagurusamy






Today's Discussion

Review of structures
Procedure oriented programming
Object-oriented programming


Structs
struct: datatype that contains a sequence of named members of
various types
Example:
struct Student {
int studentID;
float hwkScores[10];
};

Syntax:
struct newStructName{
//member declarations
};
Note: semicolon is required!
Creating structs, accessing members
Self-defined types can be used just like built-in types:
to create struct instances (variables):
Student student1; //just like: int x;
Student cs3Students[300]; //just like: int score[300];

Accessing members with the . operator:
student1.studentID = 999999;
student1.hwkScores[0] = 100;

Now consider the 3Students array: how do you..
set the studentID of the student with index 3?

output the 3rd hwkScore of the 0th student?

read the studentID of the 1st student from cin?
Information hiding principle
Lets look at another struct:
struct Date {
int day;
Month month;
// declared before: enum Month {JAN, FEB...
int year;
};
Date hiringDate[numEmployees]; //create an array of Date variables



- a human resource program/database will contain thousands of Date
variables
- what if somebody enters an invalid year into a Date variable?
- what if you have to change the internal representation of this type?
(Y2K bug....)



day: 20
month: JAN
year: 1999
day: 7
month: SEP
year: 1997
day: 15
month:MAR
year: 2000
day: 28
month: FEB
year: 1960
Information hiding principle
Information hiding principle:
provide functionality through a controlled interface,
hide the concrete implementation

Real life examples:
driving a car by operating the pedals, turning the steering
wheel, watching the speedometer
without knowing how the motor works
-- many different cars have the same interface
web-browsing
--without knowing how the content gets to your screen
--if they change some netservers out there, you wont even
notice
turning radio knobs, without understanding the circuits


Code:
instead of offering access to the internals of variables
offer functions that operate on the variables

Information hiding principle
accessible to users of
your code
accessible only to the
programmer (you)
setDate(d,m,y)

isPayDay()

increment()


int year
Month m
int day
Black box
9/25/00
Object-based programming
So far: create variables to implement functions

Now: write functions to implement objects

In object-oriented programming,

data, objects, concepts


are the main program components.

Tasks are done by operating the functional interfaces of the objects.


We will see how this works later....
How this class works


Homework
assignments,
exams


Lectures,
labs
Reading,
studying
one-on-one
instruction
One-on-one instruction is an important part! It is your responsibility
to assess your progress and to seek individualized instruction if you
need it. Be smart, get answers to your questions!
SUCCESS
Emphasis is on doing things (algorithms)
Large Programs are divided into smaller
programs known as functions.
Most of the functions share global data.
Data move openly around the system from
function to function.
Functions transform data from one form to
another.
Employs top down approach in program
design.



Emphasis is on data rather than on
procedure
Programs are divided into objects
Data structures are designed in such a way
that it characterizes the object
Functions that operate on data are ties
together in a data structure called class
Data is hidden and cannot be accesses by
external functions.
Objects may communicate to each other
with the help of functions.
New data and functions can be easily
added whenever necessary


POP OOP
C++, first example
Consider first the structure of program 1:
//Program: one_prime

//Purpose: Determine..
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int x;
//Prompt for input
cout << "Enter...";
cin >> x;
....
return 0;
}
Start with information
about the program
in this file
Tell compiler to include
libraries for I/O and math
Use standard library names
Header of main function:
program execution starts here.
By convention, return 0 if no
errors occur during execution
variable declaration
Commented code in
the body of the function
include, namespaces
#include <iostream>
if you want to use input and output commands in your program
#include <cmath>
if you want to use math functions such as:
ceil, floor, log, pow, sqrt, fabs
there are many other useful libraries available

namespaces are a new feature of C++ (part of the new standard)
Namespaces are used to structure very large software projects
In this course:
always add this line to your program
using namespace std;
Then you can use cout, cin, etc. without the prefix std::

Input and output in C++
To output text use:
cout << Hello world! \n;
\n causes the output to go to a new line.
\t horizontal tab
\a rings a bell (alert)
\r carriage return (go to beginning of current line)
\\ prints a backslash
\ prints "

To go to the next line, you can also use
cout << endl;
To output a number or the value of a variable (for example, x)
cout << x << endl;
Output statements can be chained:
char name[20]; cin >> name;
cout << Hello << name << , how are you?\n;

Input and output in C++
cout is actually an object of the class ostream_Withassign

<< symbol operates as an insertion operator, it takes two
operators.
The operand on the left must be some object of the ostream
class and right side is headed towards device.

It is also possible to cascade the insertion operator



Input

First use an output statement to tell the user what to enter
You need a variable in which you can store the users input.
int x; //if necessary, declare one.
cin >> x; //read from cin with >> operator.

>> is actually an operator, and just like other operators (e.g. +),
it can be applied to different types of arguments.
Example: float y; cin >> y; // reads a float from the standard input

Note: expressions containing >> have a value:
(cin >> y) is true if the read was successful and false if not.
Well learn later in the semester what exactly the value of an >>
expression is.


Input
cin is actually an object of the class istream_Withassign

The >> symbol operates as extraction operator

The operand on the left must be some object of the
istream_Withassign

The operand on the right must be a variable of some fundamental
data type

The value for the variable on the right side of the extraction
operator is extracted from the stream originating from the device
associated with object on the left.







Reference variables in C++
The OS maintains the addresses of each variable as it
allocates memory for them during runtime.

In order to access the value of a variable, the OS first finds
the address of the variable and then transfers control to the
byte whose address matches that of the variable.









Reference variables in C++
Steps involved in executing statement x=y

the OS first finds the address of y
the OS transfers control to the byte whose address matches this
address
the OS reads the value from the block of four bytes that starts
with this byte
the OS pushes the read value into a temporary stack
the OS finds the address of x
the OS transfers control to the byte whose address matches this
address
the OS copies the value from the stack, where it had put it earlier,
into the block of four bytes that starts with the byte whose address it
has found above
Reference variables in C++
Reference variable is nothing but a reference for an
existing variable.

It shares the memory with location with an existing
variable
Syntax: <data-type> &<ref-Var-name> = <existing variable name>

int &iref=x;

iref is a reference to x, they have separate entries in the
OS with same addresses

The change in the value of x will reflect in iref and vice
versa.
int a=10;
cout<<a;
int &refa=a;
cout<<refa;
refa=11;
cout<<a;
refa++;
cout<<a;



Reference variables in C++
int a,b;
a=100;
cout<<a;
int &refa=a;
b=refa;
cout<<b;
b++;
cout<<a<<refa<<b;

void inc(int &);
void main()
{
int x;
x=100;
inc(x);
cout<<x;
}
void inc(int &r)
{ r++;}

Functions can return by reference also
int main()
{
int x,y;
x=10,y=20;
int &r=large(x,y);
cout<<r<<endl;
r=-1;
cout<<x<<y;
return 0;
}
int &large( int &a, int &b)
{
if(a>b)
return a;
else
return b;
}


Reference variables in C++
Functions can return by reference also
int &large( int &, int &);
int main()
{
int x,y;
x=10,y=20;
large(x,y)=-1;
cout<<x<<y;
return 0;
}
int &large( int &a, int &b)
{
if(a>b)
return a;
else
return b;
}


Reference variables in C++
The name of a non-constant variable can
be placed on the left of the assignment
operator because of the valid address.

compiler executes the instrctions like-
determine the address of the variable
transfer control to the byte that has
that address
write the value on the right of the
assignment operator into the block that
begins with the byte found above


Function definitions
Example:
int min(int x, int y) Function header
{
if (x< y)
return x; Function body
else
return y;
}

Lets look at the function header first: it specifies
name of the function: min
number and type of input arguments: int x, int y
type of the return value: int
Functions that dont return a value have return type void

Body: contains code that implements the function and
returns a value of the specified type.

Function calls
Example:
int main()
{
int a=4,b=6;
cout << the min is << min(a,b) << endl;
cout << the max is << a+b-min(a,b) << endl;
return 0;
}
- function name: min
- specify concrete values for the input parameters: a,b
- after function is executed, the value of the function call
is the value that was returned.

Functions: return values vs. printing output
Many beginning programmers print the result in a function
instead of returning it.
Example:
void min(int x, int y)
{ cout << the min is ;
if(x<y)
cout << x;
else
cout << y;
}
Whats the problem with that?
you cant use the results of those functions in expressions:
a+b-min(a,b) wouldnt work
minInput = min(a,b); wouldnt work either
Distinguish functions (have a result) from procedures (a sequence
of statements without a result, return type void)!

Function declarations
1. the compiler needs to know the input-output specification of a
function before the first function call (for type checking!)
2. programmers need to know how to use the function

=> function declarations (also called function prototypes), often at
the beginning of the file

Its basically just a copy of the function header:
Example:
int min(int x, int y);

Note: declarations are not necessary if the function definition comes
before the first call of this function in the file.

For the compiler, its ok to omit the parameter names in a
declaration, but without them its hard for another programmer to
figure out how to use your function:
void compute_stats(const int [],int, int &,
int &, float &, float &);

Caution:
If you change the type, order, or number of function parameters
in the function definition, dont forget to change them in the
declaration as well.
Function declarations
Function Prototyping
A prototype describes the functions interface to the compiler

It tells the compiler the return type of the function as well as the
number, type and sequence of its formal arguments.

A function prototyping guarantees protection from errors arising out of
incorrect function calls.

A function prototyping produces automatic type conversion whenever
appropriate.

The compiler decides which function is to be called based upon the
number, type and sequence of parameters that are passed to the
function call.
Function Prototyping
In the absence of prototypes, the compiler will have to assume the
types of the returned value.

struct abc
{
char q;
int b;
float c;
};
struct abc test()
{
struct abc a1;
a1.a=x;
a1.b=10;
a1.c=1.1;
return a1;
}

int main()
{
int x;
x=test();
cout<<x;
return 0;
}

Function overloading is also known
as function polymorphism.

Function polymorphism is static in
nature because the function
definition to be executed is selected
by the compiler during compile time
itself.

an overloaded function is said to
exhibit static polymorphism.
Function Overloading
C++ allows two or more functions to have the same name with
different signatures.

Signature of a function means the number, type and sequence
of formal arguments of the function.

Depending upon the type of parameters that are passed to the
function call, the compiler decides which of the available
definitions will be invoked.
#include<iostream>
int add(int,int);
int add(int,int,int);
int main()
{
int x,y;
x=add(1,2);
y=add(1,2,3);
cout<<x<<endl<<y<<endl;
}
int add(int a,int b)
{ return (a+b); }

int add(int a,int b,int c)
{ retutn (a+b+c); }
Function Overloading
Default values for the formal arguments
of the function
it is possible to specify default values for some or all of the formal
arguments of a function.

if no value is passed for an argument when the function is called,
the default value specified for it is passed.

if the parameters are passed in the normal fashion for such an
argument, the default value is ignored.
#include<iostream>
int add(int,int,int c=0);
int main()
{
int x,y;
x=add(1,2,3);
y=add(1,2);
cout<<x<<endl<<y<<endl;

int add(int a,int b,int c)
{ return (a+b+c); }


Default values for the formal arguments
of the function
Default values can be given to
arguments of any datatypes

double sal(double,double=0.3);
void print(char=a);
Default values can be assigned to more than one argument.

Default values must be supplied from right most argument
only.

Default values must be specified in the function prototypes
and should not be specified again in the function
definitions.


Default values for the formal arguments
of the function
Inline Functions
Inline functions are used to increase the speed of execution of the
executable files.

An inline function is a function whose compiled code is inline with
the rest of the program.

The compiler replaces the function call with the corresponding
function code, so performs little faster when compared to regular
functions.

if an inline function is called repeatedly, then multiple copies of the
function definition appear in the code, so the executable program
itself becomes so large that occupies a lot of space in the memory
during runtime.
for specifying inline function
prefix the definition of the function with the inline keyword.
define the function before all functions that call it, define it in
the header file itself
#include<iostream>
inline double cube(double x) { return x*x*x; }
int main()
{
double a,b,c=13.0;
a=cube(5.0);
b=cube(4.5+6.5);
cout<<a<<endl<<b<<endl<<cube(c++)<<endl<<c<<endl;
}
Inline Functions
Inline Functions
Inline functions may give some warnings during
when function is recursive
There are looping constructs in the function
There are static variables in the function

You might also like