You are on page 1of 95

Object Oriented Programming-

Introduction
Introduction
3

Evolution of Programming Language


▫ Evolution of languages:
▫ Machine languages -- The lowest-level programming paradigms
are machine code, which directly represents the instructions (the contents of
program memory) as a sequence of numbers. This is what is necessary
for the computer, but hard for people to read
▫ Assembly languages -- these are symbolic translations of
machine code, easier for people to read. The machine
instructions are represented by mnemonics and memory
addresses can be given symbolic labels
▫ High-level procedural languages (like Pascal,
Fortran, C)
▫ Object Oriented languages (C++, Java,
Smalltalk)
4

Procedural Programming
▫ Procedural programming is a programming
paradigm, derived from structured programming
based on the concept of the procedure call.
Procedures (a type of routine or subroutine)
simply contain a series of computational steps to
be carried out.
▫ Any given procedure might be called at any point
during a program's execution, including by other
procedures or itself.
Structure of Procedure Oriented
Programming
Relationship b/w data and function
Object Oriented Programming
8

Object Oriented Programming


▫ Procedural programming uses procedures to
operate on data structures, object-oriented
programming bundles the two together, so an
"object", which is an instance of a class, operates
on its "own" data structure
9

Features of OOP
▫ 1. Emphasis is on doing rather than procedure.
▫ 2. programs are divided into what are known as objects.
▫ 3. Data structures are designed such that they characterize the
objects.
▫ 4. Functions that operate on the data of an object are tied
together in the data structure.
▫ 5. Data is hidden and can’t be accessed by external functions.
▫ 6. Objects may communicate with each other through
functions.
▫ 7. New data and functions can be easily added.
▫ 8. Follows bottom-up approach in program design.
10

Introduction
• C++ is derived from C programming language – an extension that
added object-oriented (OO) features.
- Lots of C++ syntax similar to that found in C, but there are
differences and new features.

• Popular because of the reuse of objects


– Classes – template or blueprint for an object
– Objects
– Methods

• Objects are organized in a hierarchy


– Super Classes
– Sub Classes
11

Evolution of C++
• C (1972)
• ANSI Standard C (1989)
• Bjarne Stroustrup adds features of the language Simula (an object-
oriented language designed for carrying out simulations) to C
resulting in …
• C++ (1983)-the name of the language was changed from C with
Classes to C++.
• Many new features were added around this time, the most notable of
which are virtual functions, function overloading, references and many
more.
• In 1990, Turbo C++ was released as a commercial product. Turbo C++
added a lot of additional libraries which have had a considerable impact
on C++'s development.
12

Evolution of C++
• ANSI Standard C++ (1998)-In 1998, the C++ standards committee
published the first international standard for C++ ISO/IEC 14882:1998,
which is informally known as C++98. The Standard Template Library,
which began its conceptual development in 1979, was also included
• ANSI Standard C++ [revised] (2003)
• ANSI Standard C++ (2011)
• The present C++
– A general-purpose language that is in widespread use for
systems and embedded
– The most commonly used language for developing system
software such as databases and operating system.
13

C++ - an Object-Oriented Programming Language

Other examples: C# and Java

The modern approach to developing programs

- Objects in a real-world problem are modeled as software objects


Concepts of OOP
• To allow more complex programs to be written,
object-oriented programming has been invented.
OOP takes the best of the ideas in structured
programming and combines them with powerful
new concepts that allow you to organise your
programme more efficiently.
• Object oriented programming encourage you to
decompose a problem into its constituent parts.
Concepts of OOP
• Objects- run time entities and may represent
person, place or any item that program has to
handle
• Class- objects contains data and code to
manipulate data. The entire set of data and code
of an object called CLASS.
Concept of Class
• A class is a description of a group of objects with common
properties (attributes) & behavior (operations)
– An object is an instance of a class
– e.g. Mary is an object of Student class
Jane is an object of Student class

Mary 1001
Jane 1002

name rollNo
name rollNo
Encapsulation

• Encapsulation is the mechanism that binds


together code and the data it manipulates, and
keeps them both safe from outside. In an object-
oriented language, code and data can be
combined in such a way that a self-contained
‘black box’ is created.
Encapsulation
• Within an object, code, data, or both may be private
to that object or public.
• Private code or data is known to and accessible only
by another part of the object (i.e. cannot be accessed
by a piece of the program that exists outside the
object.
• Public code or data can be accessed by other parts of
the program even though it is defined within an
object.
• Public parts of an object are used to provide a
controlled interface to the private elements of the
object.
• An object is a variable of a user-defined type. Each time
you define a new type of object, you are creating a new
data type.
• The term objects means a combination of data and
program that represent some real word
• entity.
• For example: consider an example named Amit; Amit is
25 years old and his salary is 2500.The Amit may be
represented in a computer program as an object. The
data part of the object wouldbe (name: Amit, age: 25,
salary: 2500)
Polymorphism

• Polymorphism is the quality that allows one


name to be used for two or more related but
technically different purposes.
• Polymorphism allows one name to specify a
general class of actions
INHERITANCE: AN INTRODUCTION
• Inheritance is the process by which one object can
acquire the properties of another. An object can
inherit a general set of properties to which it can add
those features that are specific only to itself.
• Inheritance is important because it allows an object
to support the concept of hierarchical classification.
Most information is made manageable by
hierarchical classification.
• The child class inherits all those qualities associated
with the parent and adds to them its own defining
characteristics.
Dynamic Binding
▫ Binding refers to the linking of a procedure call
to the code to the executed in
▫ response to the call. Dynamic binding means the
code associated with a given procedure call is not
▫ known untill the time of the call at run-time. It is
associated with a polymorphic reference depends
▫ upon the dynamic type of that reference.
C C++

C was developed by Dennis Ritchie between 1969 and


C++ was developed by Bjarne Stroustrup in 1979
1973 at AT&T Bell Labs.

C supports procedural programming paradigm for code C++ supports both procedural and object oriented
development. programming paradigms;

C does not support object oriented programming; Being an object oriented programming language C++
therefore it has no support for polymorphism, supports polymorphism, encapsulation, and
encapsulation, and inheritance. inheritance.

In C++ (when it is used as object oriented programming


In C (because it is a procedural programming language), language), data and functions are encapsulated
data and functions are separate and free entities. together in form of an object. For creating objects class
provides a blueprint of structure of the object.

In C, data are free entities and can be manipulated by


In C++, Encapsulation hides the data to ensure that
outside code. This is because C does not support
data structures and operators are used as intended.
information hiding.

C, being a procedural programming, it is a function While, C++, being an object oriented programming, it is
driven language. an object driven language.
26

Advantages of C++
▫ C++ is a highly portable language and is often the language
of selection for multi-device, multi-platform app
development.
▫ C++ is an object-oriented programming language and
includes concepts like classes, inheritance, polymorphism,
data abstraction, and encapsulation which allow code
reusability and makes programs very maintainable.
▫ C++ use multi-paradigm programming. The Paradigm
means the style of programming .paradigm concerned about
logics, structure, and procedure of the program. C++ is
multi-paradigm means it follows three paradigm Generic,
Imperative, Object Oriented.
▫ It is useful for the low-level programming language and very
efficient for general purpose.
Differences between C++ and Standard
C++
/* A traditional-style C++ program */
#include < iostream.h >
int main( ) {
/* program code */
return 0;
}
/*
A modern-style C++ program that uses
the new-style headers and namespace
*/
#include < iostream>
using namespace std;
int main( ) {
/* program code */
return 0;
}
Differences between C++ and Standard
C++
Old style header files Standard C++ headers
< math.h > < cmath >
< string.h > < cstring >
MY FIRST PROGRAM

#include < iostream >


using namespace std;
int main( ) {
// program code
cout << “Hello WORLD”
return 0;
}
#include <iostream>
using namespace std;
The #include Directive
int main()
• Preprocessor directive {
declaration(s)
statement(s)
• Inserts the contents of another file into the program return 0;
}
iostream is C++ library of input/output functions

This includes cout and cin

• Do not use ; at end of #include statement


The namespace Directive

This directive allows the cout and cin statements to be used in a


program without using the prefix std::
#include <iostream>
With this directive, may write using namespace std;

cin or cout int main()


{
declaration(s)
Otherwise, we would have to write statement(s)
return 0;
std::cout or std::cin }

Must use ; at end of namespace directive


The simplest C++ program consists of a single function named main.

The syntax of such programs is shown below:

#include <iostream>
using namespace std;

int main()
{
declaration(s)
statement(s)
return 0;
}

The portions of the program shown in blue should always be present.


The declarations specify the data that is used by the program. These
declarations can declare either constants or variables, for example.

The statements specify the algorithm for the solution to your problem.
A Simple, Yet Complete, C++ Program

Program producing output only

// Hello world program Comment

#include <iostream> Preprocessor


using namespace std; directives

int main() Function


{ named
cout << "Hello world!" << endl; main()
return 0; indicates
start of the
}
program

Ends execution
of main() which ends the
program
The cout Output Statement

• Used to display information on computer screen


• It is declared in the header file iostream
• Syntax

cout << expression;

• Uses << operator to send information to computer screen


cout << "Hello, there!";

• Can be used to send more than one item


cout << "Hello, " << "there!";
The cin Statement

• Used to read input from keyboard

• It is declared in the header file iostream

• Syntax

cin >> variable

• Uses >> operator to receive data from the keyboard and


assign the value to a variable

• Often used with cout to display a user prompt first

• May use cin to store data in one or more variables


• Can be used to input more than one value

cin >> height >> width;

• Multiple values from keyboard must be separated by spaces

• Order is important: first value entered goes to first variable, etc.


Example – Algorithm for Converting Miles to Kilometers

• Problem Input
miles distance in miles
• Problem Output
kms distance in kilometers
• Algorithm will use Conversion Formula
1 mile = 1.609 kilometers
• Formulate the algorithm that solves the problem.

• Algorithm
1. Get the distance in miles.
2. Convert the distance to kilometers by multiplying by 1.609
3. Display the distance in kilometers.

• Now convert the algorithm to program code!


Constants

Syntax
const type name = expression;

The statement must include the reserved word const, which designates
the declaration as a constant declaration.

The type specification is optional and will be assumed to be integer.

Examples
const float TAXRATE = 0.0675;
const int NUMSTATES = 50;

Convention is to use uppercase letters for names of constants.


#include < iostream >
using namespace std;
int main( ) {
// local variables
int i;
float f;
// program code
cout << "Enter an integer then a float ";

cin >> i >> f; // input an integer and a float


cout << "i= " << i << " f= " << f << "\n";
// output i then f and newline
return 0;
}
43

▫ TOKENS:

▫ The smallest individual units in program are


known as tokens. C++ has the following tokens.
▫ i. Keywords
▫ ii. Identifiers
▫ iii. Constants
▫ iv. Strings
▫ v. Operators
44

▫ KEYWORDS:

▫ The keywords implement specific C++


language feature. They are explicitly reserved
▫ identifiers and can’t be used as names for the
program variables or other user defined
program
▫ elements. The keywords not found in ANSI C
are shown in red letter.
• The standard reserved keywords are:

asm, auto, bool, break, case, catch, char, class, const,


const_cast, continue, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern,
false, float, for, friend, goto, if, inline, int, long,
mutable, namespace, new, operator, private,
protected, public, register, reinterpret_cast, return,
short, signed, sizeof, static, static_cast, struct, switch,
template, this, throw, true, try, typedef, typeid,
typename, union, unsigned, using, virtual, void,
volatile, wchar_t, while
46

▫ IDENTIFIERS:

▫ Identifiers refers to the name of variable ,


functions, array, class etc. created by
programmer. Each language has its own rule for
naming the identifiers.
▫ Rules:
▫ 1. Only alphabetic chars, digits and under score
are permitted.
▫ 2. The name can’t start with a digit.
▫ 3. Upper case and lower case letters are distinct.
▫ 4. A declared keyword can’t be used as a variable
name.
Variables

Variables
• We can define a variable as a portion of memory to
store a determined value
a = 5; b = 2; a = a + 1; result = a - b;
• Each variable needs an identifier that distinguishes
it from the others.
Identifiers
A valid identifier is a sequence of one or more
letters, digits or underscore characters (_). Neither
spaces nor punctuation marks or symbols can be part
of an identifier. Only letters, digits and single
underscore characters are valid.
• Another rule that you have to consider when
inventing your own identifiers is that they
cannot match any keyword of the C++

Note: The C++ language is a "case sensitive" language. That means that an
identifier written in capital letters is not equivalent to another one with the
same name but written in small letters.
Constants

• Constants are expressions with a fixed value.


Declared constants (const)
const int a = 100;
const char b = '\t‘

Note : Const variables values cannot be modified


after their definition.
50

Data Types
Declaration of variables
• To use a variable in C++, we must first declare it
specifying which data type we want it to be.

The syntax to declare a new variable :


data_type variable_name;

Example:
int a;
float mynumber;
Initialization of variables

• There are two ways to do this in C++


• The first one, known as c-like initialization, is done by appending
an equal sign followed by the value to which the variable will be
initialized:
type identifier = initial_value ;

For example, if we want to declare an int variable called a initialized with a


value of 0 at the moment in which it is declared, we could write:
int a = 0;

The other way to initialize variables, known as constructor


initialization, is done by enclosing the initial value between parentheses
(()):
type identifier (initial_value) ;
For example:
int a (0);
Scope of variables
Introduction to strings
• Variables that can store non-numerical values
that are longer than one single character are
known as strings.
• The C++ language library provides support for
strings through the standard string class.
string mystring = "This is a string";
string mystring ("This is a string");
55

C++ INPUT/OUTPUT
• cout is used to output (print) values.The cout object,
together with the << operator, is used to output
values/print text.
• cin is a predefined variable that reads data from the
keyboard with the extraction operator

• EXAMPLE:
• int x;
• cout << "Type a number: "; // Type a number and press
enter
• cin >> x; // Get user input from the keyboard
• cout << "Your number is: " << x; // Display the input value
56

C++ Comments
• Single-line comments start with two forward slashes
(//).
• Multi-line comments start with /* and ends with */.
57

Execution of C++ Program


• Execution of a C++ program involves four stages:
58

Compile and Execution of C++ Program

• Step 1 -Preprocessor processes the program


before the compilation
• Preprocessor include header files and expand
macros and other constants declared with # sign

• Step 2- Compiler will compile the program and


checks the error and generate the object file.
59

• Step 3-third stage of any C++ program execution


process, in this stage linker links the more than
one object files or libraries and generates the
executable file.

• Step 4-Loader loads the executable file into the


main/primary memory and program runs
C++ OPERATOR
• Operators are used to perform operations on variables
and values.
• C++ divides the operators into the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
61

• Arithmetic Operators

• Arithmetic Operators: These are the operators


used to perform arithmetic/mathematical
operations on operands. Examples: (+, -, *, /,
%,++,–). Arithmetic operator are of two types:
• Unary Operators: Operators that operates or
works with a single operand are unary operators.
For example: (++ , –)
• Binary Operators: Operators that operates or
works with two operands are binary operators.
For example: (+ , – , * , /)
62

C++ OPERATOR
• Relational Operators: These are used for
comparison of the values of two operands. For
example, checking if one operand is equal to the
other operand or not, an operand is greater than
the other operand or not etc. Some of the
relational operators are (==, >= , <= )
63

C++ OPERATOR
• Assignment Operators: Assignment operators are
used to assign value to a variable. The left side
operand of the assignment operator is a variable
and right side operand of the assignment
operator is a value.(=,+=,-=,*=,/=)
• For example:
• a = 10;
• Bitwise Operators: The Bitwise operators is used
to perform bit-level operations on the
operands.(&,|,^,<<,>>)
64

C++ OPERATOR
• Conditional Operator: Conditional operator is of
the form Expression1 ? Expression2 :
Expression3 . Here, Expression1 is the condition
to be evaluated. If the condition(Expression1) is
True then we will execute and return the result of
Expression2 otherwise if the
condition(Expression1) is false then we will
execute and return the result of Expression3. We
may replace the use of if..else statements by
conditional operators.
65

Decision making in C++


• if statement is the most simple decision making
statement. It is used to decide whether a certain
statement or block of statements will be executed
or not i.e if a certain condition is true then a
block of statement is executed otherwise not.
if(condition)
{
// Statements to execute if
// condition is true
}
66
67

• #include<iostream>
• using namespace std;

• int main()
• {
• int i = 20;

• if (i > 10)
• {
• cout<<"10 is less than 20";
• }

• cout<<"I am Not in if";
• }
68

• if (condition)
• {
• // Executes this block if
• // condition is true
• }
• else
• {
• // Executes this block if
• // condition is false
• }
69

if-else ladder
• if (condition)
• statement;
• else if (condition)
• statement;
• .
• .
• else
• statement;
70

Loops in C++
• In computer programming, a loop is a sequence
of instructions that is repeated until a certain
condition is reached.
• For Loop and While Loop- test condition is
tested before entering the loop body
• Do-While Loop- test condition is tested or
evaluated at the end of loop body.
71

Loops in C++
• A for loop is a repetition control structure which
allows us to write a loop that is executed a
specific number of times. The loop enables us to
perform n number of steps together in one line.
• Syntax:
• for (initialization expr; test expr; update expr)
•{
• // body of the loop
• // statements we want to execute
•}
72

Loops in C++
• initialization expression;
• while (test_expression)
• {
• // statements

• update_expression;
• }
73

Loops in C++
• initialization expression;
• do
•{
• // statements

• update_expression;
• } while (test_expression);
Structure of C++ program
User-Defined DataTypes

• Class: The building block of C++ that leads to


Object-Oriented programming is a Class. It is a
user-defined data type, which holds its own data
members and member functions, which can be
accessed and used by creating an instance of that
class. A class is like a blueprint for an object.
User-Defined DataTypes
• Structure: A structure is a user defined data type
in C/C++. A structure creates a data type that can
be used to group items of possibly different types
into a single type.
• struct address {
• char name[50];
• char street[100];
• char city[50];
• char state[20];
• int pin; };
User-Defined DataTypes
• Union: Like Structures, union is a user defined
data type. In union, all members share the same
memory location.
• Enumeration: Enumeration (or enum) is a user
defined data type in C. It is mainly used to assign
names to integral constants, the names make a
program easy to read and maintain.This facility
provides an alternative means for creating
symbolic constant.
• enum week { Mon,
• Tue,
• Wed,
• Thur,
• Fri,
• Sat,
• Sun };

• int main()
•{
• enum week day;

• day = Wed;

• cout << day; }
79

Functions in C++
• A function is a group of statements that together
perform a task. Every C++ program has at least one
function, which is main().You can divide up your code
into separate function.

• A function declaration tells the compiler about a


function's name, return type, and parameters. A
function definition provides the actual body of the
function.
80

• function declaration:

• return_type function_name( parameter list );


• example
• int greater(int, int);
81

• int greater(int num1, int num2) {


• // local variable declaration
• int result;

• if (num1 > num2)
• result = num1;
• else
• result = num2;

• return result;
•}
82

• Calling a Function:
• While creating a C++ function, you give a
definition of what the function has to do. To use a
function, you will have to call or invoke that
function.

• example:
• // calling a function to get max value.
• ret = greater(a, b);
83

Default parameters for function


• When you define a function, you can specify a
default value .
• This is done by using the assignment operator
and assigning values for the arguments in the
function definition. If a value for that parameter
is not passed when the function is called, the
default given value is used, but if a value is
specified, this default value is ignored and the
passed value is used instead.
84

Default parameters for function


• using namespace std;
• int add(int a, int b = 20) {
• int result;
• result = a + b;

• return (result);
•}
85
• int main () {
• int a = 100;
• int b = 200;
• int result;
• // calling a function to add the values.
• result = add(a, b);
• cout << "Total value is :" << result << endl;

• // calling a function again as follows.


• result = add(a);
• cout << "Total value is :" << result << endl;

• OUTPUT
• Total value is :300
• Total value is :120
86

Default parameters for function


• Default arguments are overwritten when calling
function provides values for them.
• Once default value is used for an argument in
function definition, all subsequent arguments to
it must have default value. It can also be stated as
default arguments are assigned from right to left.
87

Default parameters for function


• invalid function :

• int sum(int x, int y, int z=0, int w)


88

• Pointers are a symbolic representation of


addresses. They enable programs to simulate
call-by-reference as well as to create and
manipulate dynamic data structures. Its general
declaration in C/C++ has the format:
• Syntax:
• datatype *var_name;
89

Pointers
• int *ip; // pointer to an integer
• double *dp; // pointer to a double
• float *fp; // pointer to a float
• char *ch // pointer to character
90

Pointers
• // ptr can point to an address
• // which holds int data
• int *ptr;

• The Pointers share few important features like it


saves memory space, they are used to allocate
memory dynamically, it is used for file handling
etc. Pointers store address of variables or a
memory location.
91

• int main () {
• int var = 20; // actual variable declaration.
• int *ptr; // pointer variable

• ptr = &var; // store address of var in pointer variable

• cout << "Value of var variable: ";


• cout << var << endl;

• // print the address stored in ip pointer variable


• cout << "Address stored in ptr variable: ";
• cout << ptr << endl;

• // access the value at the address available in pointer


• cout << "Value of *ptr variable: ";
• cout << *ptr << endl;
Output:
• return 0; Value of var variable: 20
•} Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
92

Pointer to pointer
• A pointer to a pointer is a form of multiple
indirection or a chain of pointers. Normally, a
pointer contains the address of a variable. When
we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which
points to the location that contains the actual
value as shown below.

• Example:
• int **var;
93

• int main () {
• int var;
• int *ptr;
• int **pptr;

• var = 3000;

• // take the address of var


• ptr = &var;

• // take the address of ptr using address of operator &


• pptr = &ptr;
• // take the value using pptr
• cout << "Value of var :" << var << endl;
• cout << "Value available at *ptr :" << *ptr << endl;
• cout << "Value available at **pptr :" << **pptr << endl;

• return 0;
• }
94

References in C++
• References in C++: When a variable is declared
as reference, it becomes an alternative name for
an existing variable. A variable can be declared as
reference by putting ‘&’ in the declaration.

• A reference variable is an alias, that is, another


name for an already existing variable. Once a
reference is initialized with a variable, either the
variable name or the reference name may be used
to refer to the variable.
95

• Creating References in C++

• int i = 20;

• int& r = i;

You might also like