intro to c++

38
Object Oriented Programming through C+ + Narendra V G Dept. of CSE MIT, Manipal

Upload: kellie-warner

Post on 01-May-2017

213 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Intro to C++

Object Oriented Programming through C++

Narendra V G Dept. of CSEMIT, Manipal

Page 2: Intro to C++

Preferred text:Object-Oriented Programming with C++ bySourav SahayObject-Oriented Programming with C++ byE Balagurusamy

Page 3: Intro to C++

Today's Discussion

Review of structuresProcedure oriented programmingObject-oriented programming

Page 4: Intro to C++

Structs

• struct: datatype that contains a sequence of named members of various typesExample:struct Student {

int studentID;float hwkScores[10];

};

Syntax: struct newStructName{

//member declarations}; Note: semicolon is required!

Page 5: Intro to C++

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?

Page 6: Intro to C++

Information hiding principle

Let’s 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: 20month: JANyear: 1999

day: 7month: SEPyear: 1997

day: 15month:MARyear: 2000

day: 28 month: FEByear: 1960

Page 7: Intro to C++

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 won’t even notice• turning radio knobs, without understanding the circuits

Page 8: Intro to C++

Code:

• instead of offering access to the internals of variables

• offer functions that operate on the variables

Information hiding principle

accessible to users ofyour code

accessible only to theprogrammer (you)

setDate(d,m,y)

isPayDay()

increment()

int yearMonth mint day

“Black box”9/25/00

Page 9: Intro to C++

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....

Page 10: Intro to C++

How this class works

Homework assignments,

exams

Lectures,labs

Reading,studying

one-on-oneinstruction

One-on-one instruction is an important part! It is your responsibilityto assess your progress and to seek individualized instruction if youneed it. Be smart, get answers to your questions!

SUCCESS

Page 11: Intro to C++

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

Page 12: Intro to C++

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 informationabout the programin this fileTell compiler to includelibraries for I/O and mathUse standard library names

Header of main function: program execution starts here.

By convention, return 0 if noerrors occur during execution

variable declaration

Commented code in the body of the function

Page 13: Intro to C++

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 projectsIn this course:always add this line to your programusing namespace std;Then you can use cout, cin, etc. without the prefix std::

Page 14: Intro to C++

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 usecout << 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”;

Page 15: Intro to C++

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

Page 16: Intro to C++

Input

First use an output statement to tell the user what to enterYou need a variable in which you can store the user’s 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. We’ll learn later in the semester what exactly the value of an >>

expression is.

Page 17: Intro to C++

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.

Page 18: Intro to C++

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.

Page 19: Intro to C++

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

Page 20: Intro to C++

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.

Page 21: Intro to C++

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++;}

Page 22: Intro to C++

Functions can return by reference alsoint 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;elsereturn b;}

Reference variables in C++

Page 23: Intro to C++

Functions can return by reference alsoint &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;elsereturn 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

Page 24: Intro to C++

Function definitionsExample:int min(int x, int y) Function header{

if (x< y)return x; Function body

elsereturn y;

}

Let’s 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: intFunctions that don’t return a value have return type void

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

Page 25: Intro to C++

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.

Page 26: Intro to C++

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;

}What’s the problem with that?• you can’t use the results of those functions in expressions: a+b-min(a,b) wouldn’t work minInput = min(a,b); wouldn’t work eitherDistinguish functions (have a result) from procedures (a sequence of statements without a result, return type void)!

Page 27: Intro to C++

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

It’s 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.

Page 28: Intro to C++

For the compiler, it’s ok to omit the parameter names in a declaration, but without them it’s 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, don’t forget to change them in the declaration as well.

Function declarations

Page 29: Intro to C++

Function PrototypingA prototype describes the function’s 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.

Page 30: Intro to C++

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.

Page 31: Intro to C++

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.

Page 32: Intro to C++

#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

Page 33: Intro to C++

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.

Page 34: Intro to C++

#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’);

Page 35: Intro to C++

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

Page 36: Intro to C++

Inline FunctionsInline 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.

Page 37: Intro to C++

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

Page 38: Intro to C++

Inline FunctionsInline functions may give some warnings during

when function is recursiveThere are looping constructs in the functionThere are static variables in the function