0% found this document useful (0 votes)
34 views112 pages

Unit 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views112 pages

Unit 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

SMT KASHIBAI NAWALE COLLEGE OF

ENGINEERING
Department of Computer Engineering

Object Oriented Programming


Introduction to object oriented programming, Need of object oriented
programming, fundamentals of object oriented programming: Namespace,
objects, classes, data members, methods, messages, data encapsulation, data
abstraction and information hiding, inheritance, polymorphism, Benefits of OOP,
C++ as object oriented programming language.
C++ Programming basics, Data types, structures, enumerations, control
strucures, arrays and strings, class, object, class and data abstraction, access
specifiers, separating interface from implementation.
Functions – Function, Function Prototype, accessing function and utility
function, constructors and destructor, types of constructor, objects and memory
requirements, static members: variables and functions, inline function, friend
function -07Hours
Programming Paradigm
• Paradigm refers to style of program
• It dictate how code is organized, structured,
and executed.
1. Procedural programming
2. Object-oriented programming
Procedure-oriented Programming

• The emphasis is on procedures or functions.


• The code is organized into functions, which are self-
contained blocks of code that perform specific tasks.
• Data is often stored in variables
• Functions can manipulate the data by passing it as
parameters.
• Procedural programming focuses on breaking down a
problem into smaller tasks and organizing the code around
these tasks.
Key Features of POP
• Emphasis on Procedures/functions
• Global Data
• Top-Down Design
• Limited Reusability
• Example Languages: C, Fortran, Pascal.
Object oriented programming

• OOP centers around the concept of objects.


• An object is anything that exists in a real world.
• An object contains both data and methods/functions that
operate on that data.
• Objects interact with each other using functions.
• OOP promotes the idea of code reusability and modularity
through the use of classes and inheritance.
Object oriented programming
Simple C++ program
• Include Library Files
• Define namespace
• Write classes as per need
• Create main()

#include <iostream>
using namespace std;
int main()
{
cout<<“Hello World”;
return 0;
}
Simple C++ program
• <iostream>
– This header supports C++ I/O operations.
– processor directive #include<iostream>
– The standard output stream normally flows to the screen
– The standard input stream normally flows to the keyboard

• using namespace std;


– This tells the compiler to use the ‘std’ namespace
– If not used, function call like std::cout has to be used (scope resolution op)
– This is the namespace in which the entire Standard C++ library is declared

• main() :
– Entry point of a program.
– Execution of the code starts from this function.
Simple C++ program
• cout
– An object
– Predefined in C++ to correspond with the “standard output stream”
– cin object used for taking input.

• The Operator << (Insertion Operator)


– Used for output

• The Operator >> (Extraction Operator)


– Used for taking input
Fundamentals of OOP
• Objects
• Classes
• Namespaces
• Encapsulation
• Data abstraction and information hiding
• Inheritance
• Polymorphism
• Message Passing
• Example: Java, Python, C++.
Namespaces

• Namespace provide the space where we can define or


declare identifier i.e. variable, method, classes.
• Example: C++ standard library (std) where all the
classes, methods and templates are declared.
• Hence while writing a C++ program we usually include
the directive using namespace std;
Object

• Basic run time entity of OOP


• Contains data and code to manipulate that data
• Ex. A person, a place, a bank account
• Syntax for using object:
Class_name obj_name;
Obj_name.data;
Obj_name.function_name();
Classes

• User defined data type.


• Collection of objects of similar types
• When a class is defined, no memory is allocated but when an
object is created memory is allocated.
Simple program using class
#include<iostream>
using namespace std;
class person
{
public:
string name;
int age;
};
int main()
{
person p1;
cin>>p1.name;
cin>>p1.age;
cout<<p1.name<<p1.age;
return 0;
}
Data Member/Member Function

• Data members are nothing but variables.


• Member functions are functions declared in program

– Private Member:
• Members declared in private section
• Can be accessible within class only

– Public Member:
• Members declared in public section
• Can be accessible within the class and outside of class
Member functions in class
1. Inside class definition
class person
{
public:
string name;
int age;
void display()
{
cout<<age<<display;
}
};
Member functions in class
2. Outside class definition
class area
{
public:
float calculate(float l, float w);
};
float area::calculate(float l, float w)
{
float a;
a=l*w;
return a;
}
Access Specifiers

• Helps to implement concept of data hiding.


• Used to set restriction on access

1. Public: A public member is accessible from anywhere outside


the class but within a program.
2. Private: A private member variable or function cannot be
accessed outside the class. Only the class and friend functions
can access private members.
3. Protected: Protected members can be accessed by any subclass
(derived class) of that class.
Example: The Person class
#include<iostream>
class Calculator private
{
int a,b;
Data member
public:
void add()
{
int c=a+b; public
cout << c<< endl;
}
Member function
};
Encapsulation
• Binding together data and the functions.
• Class is example of encapsulation.
• It increases the security of data
• Encapsulation supports data protection and information
hiding.
Data abstraction
• Abstraction means displaying only essential information
and hiding the details.
• Example: a man driving a car, use of AC, washing machine
• Access specifiers are the main pillar of implementing
abstraction in C++
– Public
– Private
• Abstraction using classes
• Abstraction using header files
– Ex. Math.h header file contains pow() function
Inheritance
• The capability of a class to derive properties and
characteristics from another class is called Inheritance.
• new classes are created from the existing classes.
• The new class created is called “derived class” or “sub
class” and the existing class is known as the “base class”
or “super class”.
• allows the user to reuse the code whenever possible.
Polymorphism
• Many forms
• Same thing can exist in more than one form
• A real-life example of polymorphism is a person who at
the same time can have different characteristics.
• Function overloading
• Operator overloading
#include <iostream>
using namespace std;
Class Simple
{
public:
void func(int x)
{
cout << "value of x is " << x << endl;
}
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y<< endl;
}
};
int main()
{
Simple s1;
obj1.func(7);
obj1.func(85, 64);
}
Message Passing
• Objects communicate with one another by sending and
receiving information to each other.
• Message passing involves specifying the name of the
object, the name of the function, and the information to be
sent.
• Steps in message passing:
– Creating classes
– Creating objects from class
– Establish communication among objects using functions
Benefits of OOP

1. Eliminated redundant code using inheritance.


2. Extend use of existing classes.
3. Data hiding helps to build secure programs.
4. Easy to upgrade from small to large systems.
5. Message passing helps to communicate with external
systems.
C++ Programming basics
Variable declaration
• Variables in C++ is a name given to a memory location.
• Basic unit of storage.
• Syntax:
datatype variable_list;

• Example:
int a;
float b,c;
Rules for Naming variables in C++
• The first character of a variable must be a letter or an
underscore.
• The variable name cannot start with a digit.
• It should contain only letters, digits, underscores.
• There is no limit for the length of variable names.
• Declared/Predefined keywords cannot be used as a variable
name.
• Upper and lower case letters are distinct. (Case Sensitive )
Data Types
Data Type Size
Structure
• It is a user defined data type.
• It can store collection of data with similar or non-
similar data types.

• Difference between array and structure:


– Array can store multiple values of same data type.
– Structure can store values with different data
types.
Structure

Syntax: Variable declaration:


struct structure_name struct structure_name
{ {
member1; members;
member2; }var1,var2;
… OR
member n; Structure_name obj;
};
Structure
Example:
struct student int main()
{ {
int rollno; student s3,s4;
char name[20]; return 0;
float percentage; }
}s1,s2;
Structure

So what is the difference


between structure and class?

Members of a class are private by


default and members of a structure
are public by default.
Enumerations
• It is a user defined data type.
• It provides a way for attaching names to numbers.
• Generally used when you expect the variable to
select one value from the possible set of values
• Example: gender -> male, female
Enumerations
• Syntax:
enum enumerated-type-name
{
value1, value2,value3…..valueN
};

• Example:
enum week{Sun,Mon,Tues,Wed,Thu,Fri,Sat};

The starting code value of the first element of the enum is 0.


Enumerations
#include <iostream>
using namespace std;
enum week { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
int main()
{
week day1, day2;
day1 = Mon;
day2 = Thu;
int diff = day2 - day1;
cout << “Days between = “<< diff << endl;
if(day1 < day2)
cout <<“ Day1 comes before day2\n”;
return 0;
}
Enumerations
Explicitly specifying values for enum:

enum season
{
spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
Enumerations
#include <iostream>
using namespace std;
enum season {spring = 0, summer = 4, autumn = 8, winter = 12 };
int main()
{
season s1;
s1=winter;
cout << “Value for s1 winter = “<< << endl;
return 0;
}
Contol Structures
Control Structures are just a way to specify flow
of control in programs.
• Decision/Selection statements
• Iteration Statements (Loops)
• Jump Statements
1. Decision/Selection Structures
Used to make decision in a program
1. if statement
2. if – else
3. if – else – if (if-else ladder)
4. nested if
5. switch case statement
if statement
Syntax:
if (condition) {
// block of code to be executed if the
condition is true
}
Example:
if (a>b)
{ cout<<“a is greater”; }
if else statement
Syntax: Example
if (condition) if (a>b)
{ {
// block of code cout<<a;
} }
else else
{ {
// block of code cout<<b;
} }
if else ladder
Syntax: Example
if (condition1) if (a>b)
{ {
// block of code cout<<a;
} }
else if (condition2) else if(a==b)
{ {
// block of code cout<<“equal”;
} }
else else
{ {
// block of code cout<<b;
} }
nested if
Syntax: Example
if (condition1) int a=20,b=10,c=2;
{ if (a>b)
// block of code {
if (condition2) if(a>c)
{ {
// block of code cout<<a;
} }
}
}
switch statement

• Alternative to long if-else-if ladder


• Executes different blocks of statements based on
the value of the given expression.
• We can create different cases for different values
of the switch expression.
• We can specify any number of cases in the switch
statement but the case value can only be
of type int or char.
switch statement
Syntax:
switch (expression)
{
case value_1: // statements_1;
break;
case value_2: // statements_2;
break;
.....
.....

default: // default_statements;
break;
}
2. iteration statement / loops
• In Programming, sometimes there is a need to perform some
operation more than once or (say) n number of times.
• Loops come into use when we need to repeatedly execute a
block of statements.
}

for loop
• A For loop is a repetition control structure that allows us to
write a loop that is executed a specific number of times.
• firstly initializes, then, condition check, execute body, update

Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
}

for loop
Example 1: #include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++)
{
cout << "Hello World\n";
}
return 0;
}
}

for loop
Example 2: #include <iostream>
using namespace std;
int main()
{
int i = 99;
for (int i = 0; i < 5; i++)
{
cout << i << "\t";
}
cout << "\n" << i;
return 0;
}
}

for loop
Example 3: #include <iostream>
using namespace std;
int main()
{
int i = 99;
for ( i = 0; i < 5; i++)
{
cout << i << "\t";
}
cout << "\n" << i;
return 0;
}
}

for loop
Example 4:

#include <iostream>
using namespace std;
int main()
{
for (int i = 0, j = 10; (i + j) < 20; j++, i += 2)
{
cout << i << " " << j << "\n";
}
return 0;
}
}

for loop
Example 5:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i<5; i++)
{
for(int j=0; j<i; j++)
{
cout << “*” << “\t”;
}
cout<<“\n”;
}
return 0;
}
}

while loop
• While studying for loop we have seen that the number of iterations
is known beforehand, i.e. the number of times the loop body is
needed to be executed is known to us.
• while loops are used in situations where we do not know the exact
number of iterations of the loop beforehand.
• The loop execution is terminated on the basis of the test conditions.
• Syntax:
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
}

while loop
Example: #include <iostream>
using namespace std;
int main()
{
int i = 1; // initialization expression
while (i < 6) // test expression
{
cout << "Hello World\n";
i++; // update expression
}
return 0;
}
do while loop
• In the do-while loop, the condition is tested at the end of the
loop body, i.e do-while loop is exit controlled.
• The loop body will execute at least once irrespective of the
test condition.
• Syntax:
initialization expression;
do
{
// statements
update_expression;

} while (test_expression);
do while loop
Example: #include <iostream>
using namespace std;
int main()
{
int i = 2;
do {
cout << "Hello World\n";
i++;
} while (i < 1);
return 0;
}
3. jump statements

• jump statements are used to manipulate the flow of


the program if some conditions are met.

• It is used to terminate or continue the loop inside a


program or to stop the execution of a function.
continue

• The continue is used to execute other parts of the


loop while skipping some parts declared inside the
condition.

• Rather than terminating the loop, it continues to


execute the next iteration of the same loop.

• Used with a decision-making statement which must


be present inside the loop.
continue
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i < 10; i++)
{
if (i = = 5)
{
continue;
}
cout << i << " ";
}
}
break

• The break statement is used to terminate the whole


loop if the condition is met.

• After the condition is met, it breaks the loop and


the remaining part of the loop is not executed.

• Used with a decision-making statement which


must be present inside the loop.
break
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i < 10; i++)
{
if (i == 5)
break;
cout << i << " ";
}
return 0;
}
return

• The return statement takes control out of


the function itself.

• It is used to terminate the entire function after the


execution of the function or after some condition.

• Every function has a return statement with some


returning value except the void() function.
#include <iostream>
return
using namespace std;
int main()
{
cout << "Begin ";
for (int i = 0; i < 10; i++)
{
if (i = = 5)
return 0;
cout << i << " ";
}
cout << "end";
return 0;
}
goto

• The goto statement is used to jump directly to


some part of the program to which it is being
called.

• Every goto statement is associated with the label


which takes them to part of the program for which
they are called.

• The label statements can be written anywhere in


the program it is not necessary to use them before
or after the goto statement.
#include <iostream>
using namespace std; goto
int main()
{
ineligible:
cout<<"You are not eligible to vote!\n";
eligible:
cout<<"You are eligible to vote!";

int age = 18;


if (age < 18){
goto ineligible;
else
goto eligible;
}
Arrays
• An Array is a collection of data of the same data
type, stored at a contiguous memory location.
• Indexing of an array starts from 0.
• Elements of an array can be accessed using their
indices.
• Arrays are immutable.. Once declared, size can not
be changed
• An array can have multiple dimensions.
Arrays
Syntax:
data_type array_name[Size_of_array];
Example:
int arr[5];
Initializing Arrays
1. Initialize array with values:
int arr[5] = {1, 2, 3, 4, 5};
2. Initialize Array with Values and without Size
int arr[] = {1, 2, 3, 4, 5};
3. Initialize Array after Declaration (Using Loops)
for (int i = 0; i < N; i++) {
arr[i] = value;
}
4. Initialize an array partially
int partialArray[5] = {1, 2};
5. Initialize an array with zero
int zero_array[5] = {0};
Accessing elements
#include <iostream>
using namespace std; of Arrays
int main()
{
int arr[3] = {10, 20, 30};
cout << “1st element " << arr[0] <<
endl;
cout << “2nd element " << arr[1] <<
endl;
cout << “3rd element " << arr[2] <<
endl;
return 0;
}
Updating elements of Arrays

• Syntax:
arr[i] = new_value;
• Example:
a[3] = 40;
Traverse an Array
#include <iostream>
using namespace std;
int main()
{
int two[10] = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
for (int i = 0; i < 10; i++)
{
cout << two[i] << " ";
}
return 0;
}
Strings
• Text written in double quotes is called as string.
• At the end of string one special character is
appended automatically called null character.
• Null character = ‘\0’
• String is nothing but an array of character.
• We use char array to store and process string values
in programs.
Strings
• Syntax:
char name_variable[size];
• Example:
char a[20];
• Input a String:
cin>>a; //inputs a word
cin.getline(a,20);
• Output a string:
cout<<a;
String Manipulation functions
• Include <string.h> header file
1. strlen(char [])
2. strcmp(char [], char [])
3. stricmp(char [], char [])
4. strcat(char [], char [])
5. strncat(char [], char [], n)
6. strcpy(char [], char [])
7. strncpy(char [],char [] ,n)
Functions
• A function is a set of statements that takes input,
does some specific computation, and produces
output.
• A function runs only when it is called.
• Syntax:
return_type function_name(parameter list)
{
body of function
}
Functions
• Example:

int add(int num1, int num2)


{
int result;
result=num1+num2;
return result;
}
Function Prototype
• A function prototype tells the compiler about a
function name and how to call the function.
• Actual body of function can be defined separately.
• The function prototype consist of –

1. Return type of the data that the function will return


2. Number of arguments passed to the function
3. Data type of each passed argument
4. The order in which arguments are passed to the
function
Accessing a Function
• To use a function, you have to call or invoke a
function.
• When program calls a function, program control is
transferred to the called function.
• After function ends, control is again returned to
main program.
• Syntax:
function_name(parameters);
n = function_name(parameters);
Function Arguments
• The parameters passed to the function are
called actual parameters.
• For example: add(5,10);
• The parameters received by the function are
called formal parameters.
• For example, parameters in function definition are
formal parameters.
Function Arguments
Function Arguments
1. Pass by Value:
– In this parameter passing method, values of actual parameters
are copied to the function’s formal parameters.
– The actual and formal parameters are stored in different
memory locations so any changes made in the functions are
not reflected in the actual parameters of the caller.

2. Pass by Reference:
– Both actual and formal parameters refer to the same locations,
so any changes made inside the function are reflected in the
actual parameters of the caller.
Default values for parameters
• While defining a function, we can
specify default value for last Example:
parameters.
• This value is used if corresponding int sum(int a, int b = 20)
argument is left blank while {
calling. int result = a + b;
return result;
• Once a default value is used for an
}
argument in the function definition,
all subsequent arguments to it must
have a default value as well.
Constructor
• Constructor is special member function of a class that is
executed whenever we create an object of that class.
• Very useful for setting initial values for member
variables.
• Constructor has same name as the class.
• They do not return values; hence they do not have a
return type.
• They are automatically called when objects are created.
Types of Constructor

1. Default constructor

2. Parameterized constructor

3. Copy constructor
1. Default Constructor
• Default constructor is the constructor which
doesn’t take any argument.
• It has no parameters.
• It is also called a zero-argument constructor.
2. Parameterized Constructor
• It is possible to pass arguments to constructors.
• To create a parameterized constructor, simply add
parameters to it the way you would to any other
function.
• When you define the constructor’s body, use the
parameters to initialize the object.
3. Copy Constructor
• A copy constructor is a member function that
initializes an object using another object of the
same class.
Destructor
• A destructor is also a special member function like
a constructor.
• Destructor destroys the class objects created by
the constructor.
• Destructor has the same name as their class name
preceded by a tilde (~) symbol.
• There can be only one destructor in a class.
• Destructor neither requires any argument nor
returns any value.
Destructor
• Destructor release memory space occupied by the
objects created by the constructor.
• It is automatically called when an object goes out
of scope i.e. when function or program ends.
Objects and memory
requirements
• Memory Allocation : reserving memory for
variables, arrays, objects, etc.
• When we create variables or objects, memory is
allocated to them.
• Types:
1. Static memory allocation
2. Dynamic memory allocation
Objects and memory
requirements
Static Memory Allocation
• Allocating fixed amount of memory for data at
starting of the program or function.

• Drawbacks:
– Allocated memory can be larger, resulting in wastage
of memory
– Allocated memory can be lesser, resulting in program
failure.
Objects and memory
requirements
Dynamic Memory Allocation
• Size of memory is decided according to
program/user requirements.
• Memory can be allocated or de-allocated at any
stage of program.
• Dynamic memory allocation uses pointers.
• Keyword new is used to allocate a memory and
delete to free a memory.
new
• Allocating memory to one variable/object:
pointer-variable = new data-type;

• Allocation memory to array


pointer-variable = new data-type[size];

• the pointer variable is the pointer of type data-type.


• Data type could be any built-in or user defined data
type.
delete
• De-allocating memory to one variable/object:
delete pointer-variable;

• De-allocation memory to array


delete pointer-variable[];
Friend Class

• A friend class can access private and protected


members of other classes in which it is declared as a
friend.
• It is sometimes useful to allow a particular class to
access private and protected members of other
classes.
• Syntax:
friend class class_name;
Friend Function

• Like a friend class, a friend function can be granted


special access to private and protected members of a
class in C++.
• They are the non-member functions that can access
and manipulate the private and protected members
of the class for they are declared as friends.
• A friend function can be:
1. A global function
2. A member function of another class
Friend Function

Syntax:
• for a global function:

friend return_type function_name(args);

• for a member function of another class:

friend return_type class_name::function_name (args);


Static Data Members
• We can define class members static using static
keyword.
• When we declare a member of a class as static it
means no matter how many objects of the class are
created, there is only one copy of the static member.
• A static member is shared by all objects of the class.
• All static data is initialized to zero when the first
object is created, if no other initialization is present.
Static Member Function

• A static member function can be called even if no


objects of the class exist.
• Static functions are accessed using only the class name
and the scope resolution operator ::.
• A static member function can only access static data
member, other static member functions and any other
functions from outside the class.
Static Members
• Syntax for declaration:
static data_type variable_name;
static return_type function_name();

• Syntax for accessing:


class_name::data_member
class_name::function_name(parameter)
Inline functions
• C++ provides inline functions to reduce the
function call overhead.
• When inline function is called whole code of the
inline function gets inserted or substituted at the
point of the inline function call.
• This substitution is performed by the C++
compiler at compile time.
• An inline function may increase efficiency if it is
small.
Inline functions
Inline functions in class
class Simple
{
public:
inline void display()
{ cout<<“inline”; }
};
int main()
{
Simple s;
s.display();
}
Inline functions
• Advantages:
1. The speed of execution of a program increases.
2. Readability of the program increases.
3. It does not require function calling overhead.
4. It also save overhead of return call from a function.
• Disadvantages:
1. The size of the executable file increases.
2. More memory is required as the body of inline function is
inserted in the place of function call.
3. Not suitable for too long, complicated or recursive function.
END..

You might also like