Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 70

15SE201J

Object Oriented Programming in C++


John Blesswin (101922)
Department of Computer Science and Engineering
SRM University

Book to follow

Object-Oriented Programming in C++, 4th Edition by Robert


Lafore

The C++ Programming Language, 4th Edition by Bjarne


Stroustrup

UNIT I : Introduction to OOP

Need of Object-Oriented Programming - Comparison of


procedural programming and Object-Oriented Programming

Characteristics of Object-Oriented Languages

C++ Programming Basics: Basic Program Construction

Data Types, Variables, Constants

Type Conversion, Operators, Library Functions

Loops and Decisions, Structures

Functions : Simple Functions, Passing arguments, Returning


values, Reference Arguments.

Recursion, Inline Functions, Default Arguments

Storage Classes

Arrays , Strings
3

Programming paradigm

Different approaches to build solutions to specific type of


problems

OOP Introduction

Object-oriented programming(OOP) is aprogramming


paradigmbased upon objects (having both data and
methods) that aims to incorporate the advantages of
modularity and reusability.

Objects, which are usually instances of classes, are used


to interact with one another to design applications and
computer programs.

Procedural programming

List of instructions to tell the computer what to do

Object oriented programming

Component of a program that knows how to perform


certain actions and how to interact with other elements of
the program

I am going to walk
(method)

Features of OOP

Bottomup approach in program design

Programs organised around objects, grouped in classes

Focus on data with methods to operate upon objects data

Interaction between objects through functions

Reusability of design through creation of new classes by


adding features to existing classes

Comparison
Procedural Oriented

Object Oriented

Program is divided into small Program is divided into small


parts called Functions
parts called Objects
Global and Local data

Has access specifiers : Public,


Private, Protected

Doesnt have any proper way Provides data hiding and


for hiding data
security
Eg: C, VB, FORTAN

Eg: C++, JAVA, VB.NET

Characteristics of Object-Oriented
Languages

Object

Class

Data Hiding and Encapsulation

Dynamic Binding

Message Passing

Inheritance

Polymorphism

C++ Programming Basics: Basic Program


Construction
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}

Header files

The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively recent addition to C++.

Single line comment.

The line int main() is the main function where program execution begins.

The next line return 0; terminates main( )function and causes it to return the
value 0 to the calling process.
1

Compile and Execute

Open a text editor and add the code.


Save the file as: hello.cpp
Open a command prompt / Terminal and go to the directory
where you saved the file.
Type g++ -o output hello.cpp and press enter to compile your
code. If there are no errors in your code the command prompt
will take you to the next line and would generate output
executable file.
Now, type ' ./output to run your program.

Basics

In C++, the semicolon is a statement terminator.

A C++ identifier is a name used to identify a variable,


function, class, module, or any other user-defined item. An
identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters,
underscores, and digits (0 to 9).

C++ does not allow punctuation characters such as @, $,


and % within identifiers.

C++ is a case-sensitive programming language. (Thus,


Name and name are two different identifiers in C++)

C++ Keywords
Table 1 Keywords
asm

else

new

this

auto

enum

operator

throw

bool

explicit

private

TRUE

break

export

protected

try

case

extern

public

typedef

catch

FALSE

register

typeid

char

float

reinterpret_cast

typename

class

for

return

union

const

friend

short

unsigned

const_cast

goto

signed

using

continue

if

sizeof

virtual

default

inline

static

void

delete

int

static_cast

volatile

do

long

struct

wchar_t

double

mutable

switch

while

dynamic_cast

namespace

template 1

Primitive Built-in Data Types

Following table lists down six basic C++ data types:


Type

Keyword

Boolean

bool

Character

char

Integer

int

Floating point

float

Double floating point

double

Valueless

void

basic types can be modified using one or more of these type


modifiers:
signed
unsigned
short
long

Data-types with its ranges


Type

Typical Bit Width

Typical Range

char

1byte

-128 to 127 or 0 to 255

unsigned char

1byte

0 to 255

signed char

1byte

-128 to 127

int

4bytes

-2147483648 to 2147483647

unsigned int

4bytes

0 to 4294967295

signed int

4bytes

-2147483648 to 2147483647

short int

2bytes

-32768 to 32767

unsigned short
int

2bytes

0 to 65,535

signed short int

2bytes

-32768 to 32767

long int

4bytes

-2,147,483,648 to
2,147,483,647

signed long int

4bytes

-2,147,483,648 to
2,147,483,647

unsigned long
int

4bytes

0 to 4,294,967,295

float

4bytes

+/- 3.4e +/- 38 (~7 digits)

double

8bytes

1 308 (~15 digits)


+/- 1.7e +/-

Example 1
#include <iostream>
using namespace std;
int main()
{
cout <<
cout <<
cout <<
cout <<
cout <<
cout <<
return 0;
}

"Size
"Size
"Size
"Size
"Size
"Size

of
of
of
of
of
of

char : " << sizeof(char) << endl; Size of char : 1


int : " << sizeof(int) << endl;
Size of int : 4
short int : " << sizeof(short int) <<Size
endl;
of short int : 2
long int : " << sizeof(long int) << endl;
Size of long int : 8
float : " << sizeof(float) << endl; Size of float : 4
double : " << sizeof(double) << endl;
Size of double : 8

C++ Variables

A variable definition means to tell the compiler where and how


much to create the storage for the variable.
#include <iostream>
using namespace std;
int main ()
{
// Variable definition:
int a, b;
int c;
float f;

datatype variable_list;
30
23.3333

// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
cout<<c<<endl<<f;
return 0;
1

Declaration & Initialization

Variable must be declared before they are used. Usually it is


preferred to declare them at the starting of the program, but in
C++ they can be declared in the middle of program too, but
must be done before using them.
int i;
// declared but not initialised
char c;
int i, j, k; // Multiple declaration
int i; // declaration
i = 10; // initialization
int i=10;
//initialization and declaration in same step
int i=10, j=11;

Scope of variables
Global Variables
Local variables
include <iostream>
using namespace std;
int x;
// Global variable
declared
int main()
{
int a;
// Local variable
declared
x=10;
// Initialized once
cout <<"first value of x = "<< x;
x=20;
// Initialized again
a=10;
// Initialized once
cout <<"Initialized again with value =
"<< x;
}

Special types of variable

Final - Once initialized, its value cant be changed.


Static - These variables holds their value between function
calls.
#include <iostream.h>
using namespace std;
int main()
{
final int i=10;
static int y=20;
}

Constants
There are two simple ways in C++ to define constants:
Using #define preprocessor.
#define identifier value
Using const keyword.
const type variable = value;
#include <iostream>
using namespace std;

50

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{

int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
2

The const keyword


#include <iostream>
using namespace std;

50

int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


cout << area;
cout << NEWLINE;
return 0;

Type conversions

A cast is a special operator that forces one data type to be


converted into another.
Implicit type conversions
Explicit type conversions
(type) expression

Explicit type conversions


Line 1 - Value of (int)a is :21
Line 2 - Value of (int)b is :10

#include <iostream>
using namespace std;

main()
{
double a = 21.09399;
float b = 10.20;
int c ;

c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ;
c = (int) b;
cout << "Line 2 - Value of (int)b is :" << c << endl ;
return 0;

Implicit type conversions


#include <iostream>
main()
{
int i = 2;
short s = i; // convert from int to short
std::cout << s;

double d = 0.1234;
float f = d;
std::cout << f;
}

2
0.1234

return 0;

Operators

Operators are special type of functions, that takes one or more


arguments and produces a new value.

Types of Operators

Assignment Operator
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Unary Operators
Ternary Operator
Comma Operator

Operators

Assignment Operator

Operates '=' is used for assignment, it takes the right-hand side (called
rvalue) and copy it into the left-hand side (called lvalue). Assignment
operator is the only operator which can be overloaded but cannot be
inherited.
int x=10;

Arithmetic Operators

Addition (+) , subtraction (-) , diversion (/) multiplication (*) and


modulus (%) are the basic mathematical operators. Modulus operator
cannot be used with floating-point numbers.
int x=10;
x += 4 // will add 4 to 10, and hence assign 14 to X.
x -= 5 // will subtract 5 from 10 and assign 5 to x.

Operators

Relational Operators

These operators establish a relationship between operands. The


relational operators are : less than (<) , grater than (>) , less than or equal
to (<=), greater than equal to (>=), equivalent (==) and not equivalent (!
=).
int x = 10; //assignment operator
x=5;
// again assignment operator
if(x == 5) // equivalent relational operator, for comparison
{
cout <<"Successfully compared";
}

Operators

Logical Operators
Operator Description

Example

&&

Called Logical AND


operator. If both the
operands are non-zero,
then condition becomes
true.

(A && B) is false.

||

Called Logical OR Operator. (A || B) is true.


If any of the two operands
is non-zero, then condition
becomes true.

Called Logical NOT


Operator. Use to reverses
the logical state of its
operand. If a condition is
true, then Logical NOT
operator will make false.

!(A && B) is true.

Operators

Bitwise operators

Bitwise operator works on bits and perform bit-by-bit operation. The


truth tables for &, |, and ^ are as follows:
p

p&q

p|q

p^q

Operators

A = 0011 1100
B = 0000 1101

Bitwise operators
Operator Description

Example

<<

Binary Left Shift Operator. The left


operands value is moved left by the
number of bits specified by the right
operand.

A << 2 will give 240 which is 1111


0000

>>

Binary Right Shift Operator. The left


operands value is moved right by the
number of bits specified by the right
operand.

A >> 2 will give 15 which is 0000


1111

Operators

Unary Operators

These are the operators which work on only one operand. There are
many unary operators, but increment + + and decrement -- operators are
most used.

Ternary Operator
The ternary if-else ? : is an operator which has three operands.
int a = 10;
a > 5 ? cout << "true" : cout << false";

Comma Operator

This is used to separate variable names and to separate expressions.


In case of expressions, the value of last expression is produced and used.
int a,b,c; // variables declaration using comma operator
3

Library Functions

This functions perform file access, mathematical


computations and data conversions, among other things.
Table 1 Mathematical Functions (cmath)
Function

Meaning

sin(x)

Sine of an angle x (measured in


radians)

cos(x)

Cosine of an angle x (measured in


radians)

tan(x)

Tangent of an angle x (measured in


radians)

exp(x)

Exponential function of x (ex)

log(x)

logarithm of x

sqrt(x)

Square root of x

pow(x,
y)

x raised to the power y

abs(x)

Absolute value of integer number x


3

Library Functions
Table 2 Character Functions (cctype)
Function

Meaning

isalpha(c)

It returns True if C is an uppercase letter and


False if c is lowercase.

isdigit(c)

It returns True if c is a digit (0 through 9)


otherwise False.

isalnum(c)

It returns True if c is a digit from 0 through 9 or


an alphabetic character (either uppercase or
lowercase) otherwise False.

islower(c)

It returns True if C is a lowercase letter


otherwise False.

isupper(c)

It returns True if C is an uppercase letter


otherwise False.

toupper(c)

It converts c to uppercase letter.

tolower(c)

It converts c to lowercase letter.


3

Decision Making
Decision making is about deciding the order of execution of
statements based on certain conditions or repeat a group of
statements until certain specified conditions are met. C++
handles
decision-making
by
supporting
the
following
statements,
if statement
switch statement
conditional operator statement
goto statement

Decision Making with if statement


The if statement may be implemented in different forms
depending on the complexity of conditions to be tested. The
different forms are,
Simple if statement
If....else statement
Nested if....else statement
else if statement
int a = 5;
if(a > 4)
cout << "success";
if(27)
cout << "hello";

Looping

In
any
programming
language, loops are used to
execute a set of statements
repeatedly until a particular
condition is satisfied.
There are 3 type of loops in
C++ language

while loop
for loop
do-while loop

while loop

while loop can be address as an entry control loop. It is


completed in 3 steps.
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}

for loop

for loop is used to execute a set of statement repeatedly until


a particular condition is satisfied. we can say it an open ended
loop. General format is,
for(initialization; condition ; increment/decrement)
{
statement-block;
}

Nested for loop


for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
4

do while loop

do statement evaluates the body of the loop first and at the


end, the condition is checked using while statement.
do
{
....
.....
}
while(condition);

Jumping out of loop

break : When break statement is encountered inside a loop,


the loop is immediately exited and the program continues
with the statement immediately following the loop.

continue : It causes the control to go directly to the testcondition and then continue the loop process.

C++ structures

Structure is the collection of variables of different types


under a single name for better visualisation of problem.
struct person
{
char name[50];
int age;
float salary;
};

How to define a structure variable?


person bill;

#include <iostream>
using namespace std;

Structure Example 1
Enter Full name: Magdalena Dankova
Enter age: 27
Enter salary: 1024.4
Displaying Information.
Name: Magdalena Dankova
Age: 27
Salary: 1024.4

struct person {
char name[50];
int age;
float salary;
};
int main() {
person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout
cout
cout
cout
}

4}

<< "\nDisplaying Information." << endl


<< "Name: " << p1.name << endl;
<<"Age: " << p1.age << endl;
<< "Salary: " << p1.salary;

return 0;

C++ Functions

Functions are used to provide modularity to a program.


Creating an application using function makes it easier to
understand, edit, check errors etc.
Library functions
User defined functions
return-type function-name (parameters)
{
// function-body
}

Declaring, Defining and Calling


Function
#include < iostream>
using namespace std;
int sum (int x, int y); //declaring function
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}
int sum (int x, int y) //defining function
{
return (X + y);
}

Calling a function

Functions are called by their names. If the function is


without argument, it can be called directly using its name.
But for functions with arguments, we have two ways to
call them,

Call by Value

Call by Reference

Call by value
#include < iostream>
using namespace std;

#include < iostream>


using namespace std;

void calc(int x);

int calc(int x);


int main()
{
int x = 10;
x = calc(x);
printf("%d", x);
}

int main()
{
int x = 10;
calc(x);
cout<<x;
}
void calc(int x)
{
x = x + 10 ;
}

int calc(int x)
{
x = x + 10 ;
return x;
}

10

20
4

Call by reference
#include < iostream>
using namespace std;
void calc(int *p);
int main()
{
int x = 10;
calc(&x);
// passing address of x as argument
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}
20
5

Recursion
In recursion, a function calls itself until condition is
satisfied.
#include
<iostream>
Enter a number to find factorial: 4

using namespace std;

Factorial of 4 = 24

int factorial(int);
int main() {
int n;
cout<<"Enter a number to find factorial: ";
cin>>n;
cout<<"Factorial of "<<n<<" = "<<factorial(n);
return 0;
}
int factorial(int n) {
if (n>1) {
return n*factorial(n-1);
}
else {
return 1;
}
}
5

How recursion works?

Inline functions

C++ inline function is powerful concept that is commonly


used with classes. If a function is inline, the compiler
places a copy of the code of that function at each point
where the function is called at compile time.

Inline function Example 1


Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

#include <iostream>

using namespace std;

inline int Max(int x, int y)


{
return (x > y)? x : y;
}

// Main function for the program


int main( )
{

cout << "Max


cout << "Max
cout << "Max
return 0;

(20,10): " << Max(20,10) << endl;


(0,200): " << Max(0,200) << endl;
(100,1010): " << Max(100,1010) << endl;

Default arguments

Default arguments Example 1


#include <iostream>
using namespace std;
void display(char = '*', int = 1);
int main() {
cout<<"No argument passed:\n";
display();
cout<<"\n\nFirst argument passed:\n";
display('#');
cout<<"\n\nBoth argument passed:\n";
display('$', 5);
return 0;
}
void display(char c, int n){
for(int i = 1; i <=n; ++i) {
cout<<c;
}
cout<<endl;
}

No argument passed:
*
First argument passed:
#
Both argument passed:
$$$$$

Storage Classes

Storage classes are used to specify the lifetime and scope


of variables. How storage is allocated for variables and
How variable is treated by complier depends on these
storage classes.
These are basically divided into 5 different types :

Global variables
Local variables
Register variables
Static variables
Extern variables

Global variables

These are defined at the starting , before all function bodies and
are available throughout the program.

Storage Classes

Local variables
They are defined and are available within a particular
scope. They are also called Automatic variable.

Register variables
This is also a type of local variable. This keyword is
used to tell the compiler to make access to this variable
as fast as possible. Variables are stored in registers to
increase the access speed.

Storage classes

Static variable
Static variables are the variables which are initialized &
allocated storage only once
void fun()
{
static int i = 10;
i++;
cout << i;
}
int main()
{
fun();
// Output = 11
fun();
// Output = 12
fun();
// Output = 13
}

Storage classes

Extern variables
This keyword is used to access variable in a file which is
declared & defined in some other file, that is the
existence of a global variable in one file is declared
using extern keyword in another file.

Arrays

An array is a sequence of variable that can store value of


one particular data type.

Defining Arrays :

type array_name[size];
int age[5];

Array Initialization int


:

It is not necessary to write the size of an array during


array declaration.

age[5] = {12, 3, 4, 3, 9};

int age[ ] = {12, 3, 4, 3, 9};


6

Arrays Example 1
Enter 5 numbers: 4
-3
5
2
0
First number: 4
Last number: 0

nclude <iostream>
sing namespace std;

nt main()
int n[5];
cout<<"Enter 5 numbers: ;
Storing 5 number entered by user in an array using for loop. */
for (int i = 0; i < 5; ++i) {
cin>>n[i];
}

cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0]


cout<<"Last number: "<<n[4];
// last element of an array is n[SIZE_OF_ARRAY return 0;

C++ Multidimensional Arrays

C++ allows programmer to create array of an array


known as multidimensional arrays.

int x[3][4];

Two Dimensional Arrays Example 1


#include <iostream>
using namespace std;

test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1

int main()
{
int test[3][2] = {
{2, -5},
{4, 0},
{9, 1}
};
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 2; ++j)
{
cout<< "test["<< i << "][" << ;j << "] = " << test[i]
[j]<<endl;
}
}
return 0;
}
6

Strings

Two types of strings:

Strings that are objects of string class (The Standard C++ Library string
class
C-strings (C-style Strings)
char str[] = "C++";
str is a string and it holds 4 character. Although, "C++" has 3
character, the null character \0 is added to the end of the string
automatically.
char str[4] = "C++";

Other ways of defining the string:


char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};

C- Strings
S.No

Function & Purpose

strcpy(s1, s2); Copies string s2 into string s1.

strcat(s1, s2); Concatenates string s2 onto the end of


string s1.

strlen(s1); Returns the length of string s1.

strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less


than 0 if s1<s2; greater than 0 if s1>s2.

strchr(s1, ch); Returns a pointer to the first occurrence


of character ch in string s1.

strstr(s1, s2); Returns a pointer to the first occurrence


of string s2 in string s1.
6

C-Strings Example 1
#include <iostream>
using namespace std;

Enter a string: C++


You entered: C++

int main() {
char str[100];
cout<<"Enter a string: ";
cin>>str;
cout<<"You entered:
"<<str<<endl;
cout<<"\nEnter another string: ";
cin>>str;
cout<<"You entered:
"<<str<<endl;
return 0;
}

Enter another string: Programming is fun.


You entered: Programming

C-Strings Example 2

#include <iostream>
#include <cstring>
using namespace std;

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

int main ()
{
char str1[10] =
char str2[10] =
char str3[10];
int len ;

"Hello";
"World";

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << en

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << end
// total lenghth of str1 after concatenation
len = strlen(str1);
cout << "strlen(str1) : " << len << endl;
}

return 0;

#include <iostream>
#include <string>

String Class Example 3

using namespace std;

str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10

int main ()
{
string str1 =
string str2 =
string str3;
int len ;

"Hello";
"World";

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;
}
6

return 0;

Discussions

C++ is a middle-level programming language developed


by Bjarne Stroustrup starting in 1979 at Bell Labs. C++
runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX.

For more details, refer http://srmnotes.weebly.com.

You might also like