SlideShare a Scribd company logo
1 of 87
FOUNDATION OF
OBJECT-ORIENTED
PROGRAMMING
By- Ms. Dipali K. Pawar
ME(Comp), BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
Unit I
Contents
• Introduction to procedural, modular, object-oriented and generic programming techniques
• Limitations of procedural programming
• Need of object-oriented programming
• fundamentals of object-oriented programming:
• objects, classes, data members, methods, messages, data encapsulation, data abstraction and information hiding,
inheritance, polymorphism.
• Inline functions
• Function overloading
• call by value and call by reference, return by reference,
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Survey of Programming Techniques
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
 The development of software product using well-defined scientific principles,
methods and procedures is called as Software engineering.
 For developing software, we have first made design for software.
 Software designing is one of the phases of software development cycle.
 There are some approaches for software designing process.
Survey of Programming Techniques
Unstructured Programming
Procedural Programming
Modular Programming
Object-oriented programming
Generic programming
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Unstructured Programming
 Only one program i.e., main program
 All the sequences of commands or
statements in one programs called main
program
 Hole program must be written in single
continuous way; there is no stop or
broken block.
 Example: Assembly language, Old basic
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Fig. 1.1.1 Typical structure of unstructured program
Structured Programming
 Also called as Procedural
programming(POP)
 For each task procedure is created
called as function
 The procedures are called from main
program
 Example: COBOL, FORTRAN, C
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Fig. 1.1.2 Typical structure of structured programs
Modular Programming
 Procedures with some common
functionality are grouped together into
separate modules
 Program is categorized into several
smaller modules
 Each module can have its own data
 Example: C, C++
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Fig. 1.1.3 Typical structure of modular programs
Object Oriented Programming(OOP)
 Works on objects which is considered
smallest unit of the object-oriented
languages
 Focuses more on data rather than
procedures
 Data structures are designed such that
they characterize the objects
 Example: C++, java
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Fig. 1.1.4 Organization of data and functions in OOP
Example of addition of two numbers
Unstructured Programming Structured Programming Object Oriented Programming
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
clrscr();
cout << "Enter the first number";
cin >> a;
cout << "Enter the second number";
cin >> b;
c=a+b;
cout << "The sum is:" << c;
return 0
}
#include<iostream>
using namespace std;
int add(int,int);
void main()
{
int a,b,c;
clrscr();
cout << "Enter the first number";
cin >> a;
cout << "Enter the second number";
cin >> b;
c=add(a,b);
cout<<"The sum is:" << c;
getch();
}
int add(int x,int y)
{
int z=x+y;
return z;
}
#include<iostream >
using namespace std;
class Addition
{
int a,b,c;
public:
void read()
{
cin >> a;
cin >> b;
}
void add()
{
c=a+b;
}
void display()
{
cout << "The sum is:" << c;
}
};
void main()
{
Addition obj;
cout << "Enter the
numbers";
obj.read();
obj.add();
obj.display();
getch();
}
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Generic Programming
 Refers to writing code that will work for many types of data.
 It is implemented to increase the efficiency of the code.
 It enables the programmer to write a general algorithm which will work with all data
types.
 It eliminates the need to create different algorithms if the data type is an integer,
string or a character.
 Generics can be implemented in C++ using Templates.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Generic Programming using Template Example in C++
 A generic function that can be used for different data types.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include <iostream>
using namespace std;
// One function works for all data types.
// This would work even for user defined types
// if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;
return 0;
}
Output:
7
7.0
g
int myMax(int x, int y)
{
return (x > y) ? x : y;
}
double myMax(double x, double y)
{
return (x > y) ? x : y;
}
char myMax(char x, char y)
{
return (x > y) ? x : y;
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Feature Procedure oriented Programming Object oriented Programming
Divided Into In POP Program is divided into small parts called functions. In OOP, program is divided into parts called objects.
Importance In POP, Importance is not given to data but to functions as well as
sequence of actions to be done.
In OOP, Importance is given to the data rather than procedures or
functions because it works as a real world.
Approach POP follows Top-Down approach. OOP follows Bottom-Up approach.
Access Specifiers POP does not have any access specifier OOP has access specifiers named Public, Private, Protected, etc.
Data Moving In POP, Data can move freely from function to function in the
system.
In OOP, objects can move and communicate with each other
through member functions.
Expansion To add new data and function in POP is not so easy. OOP provides an easy way to add new data and function.
Data Access
In POP, Most function uses Global data for sharing that can be
accessed freely from function to function in the system.
In OOP, data can not move easily from function to function, it can
be kept public or private so we can control the access of data.
Data Hiding
POP does not have any proper way for hiding data, so it is less
secure.
OOP provides Data Hiding so provides more security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function
Overloading and Operator Overloading.
Examples Examples: C, VB, FORTRAN, Pascal. Examples: C++, JAVA, VB.NET, C#.NET.
Limitations of Procedural Programming
 Poor real-world model.
 No importance to data.
 No privacy.
 No true reuse.
 Functions and data should be treated equally.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Features of Object-Oriented Programming
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.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Need of Object-Oriented Programming
• To overcome the drawbacks of the POP.
• Code Reuse and Recycling: objects are created for object-oriented programs can easily be reused in other programs.
• Design benefits: Large programs are difficult to write. Object oriented programs force designers to go through an extensive
planning phase, which makes for better designs with less flaws. In addition, once a program reaches a certain size. Object
oriented programs are actually easier to program than non-object-oriented once.
• Software maintenance: Programs are not disposable. An object-oriented program is much easier to modify and maintain
than a non-object-oriented program. So, although a lot of work is spent before the program is written, less work is needed
to maintain it over time.
• Simplicity: The objects in case of OOP are close to the real-world objects, so the complexity of the program is reduced
making the program structure very simple and clear. For example by looking at the class Mobile_phone, you can simply
identify with the properties and behavior of an actual mobile phone. This makes the class Mobile_phone very simple and
easy to understand.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Fundamentals of Object-Oriented Programming Languages
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Objects
• Classes
• Data members
• Methods and Messages
• Data encapsulation
• Data abstraction and information hiding
• Inheritance
• Polymorphism
• Dynamic Binding
Classes
 Class is a template/blue-print for real-world
entities from which objects are created.
 It is a group of similar objects.
 It is a logical entity.
 Classes define states as instance variables
and behaviors as instance methods.
 Instance variables are also known as
member variable
 It doesn’t allocated memory when it is
created.
 Class is declared once.
 Classes declared using class keyword
Syntax: class ClassName{}
E.g., class Student{};
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Properties Behavior
• Color
• Cost
• Battery Life
• Make Calls
• Watches
Videos
• Play Games
Fig. 1.2.1 Example of Mobile as Class
Objects
 Objects are specific instances of a class.
 It is an entity that has states and behaviors.
 State tells how the object looks or what properties it has.
 Behavior tells what the object does.
 Object is a physical entity.
 Object is created many times as per requirement.
 Object allocates memory when it is created.
 Objects created as:
Syntax: ClassName ObjectName;
E.g., Student stud;
Student stud1, stud2;
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Objects
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Fig. 1.2.2 Example of Mobile as Class and their different brands of mobile as objects
Data Members
 The data members are variables that are declared within the class.
 These members are declared along with data types.
 The access specifier to these members can be public, private or protected.
 These data members can be accessible by main() function using the object of a class.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Method and Message
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
 Object is an instances of a class. Every object consists of both data attributes and methods. The data
attributes of every object are manipulated by the methods. These objects in the program communicate
with each other by sending messages.
 Message passing is the method of exchanging messages among objects.
 A Message for an object is a request for execution of a procedure, and therefore will invoke a
function (procedure) in the receiving object that generates the desired results.
 Message passing involves specifying the name of object, the name of the function (message) and
the information to be sent.
 Example: Employee.Salary(name);
object
message
information
#include <iostream.h>
using namespace std;
class Student
{
// Access specifier
public:
// Data Members/Properties/Attributes/instance variable
string name;
// Member Functions/operations/methods/instance method
void printname()
{
cout << “Student name is: " << name;
}
};
int main()
{
// Declare an object of class Student
Student stud;
// accessing data member
stud. name = "ABC";
// accessing member function
stud.printname();
return 0;
}
class ClassName
{
Access Specifiers; //public, private, protected
Data Members/ Instance Variable/ Properties/ Attributes;
//variables to be used
Member functions()/ Instance Methods()/ Operations()/ Methods()
//Methods to access data methods
{
//function body
}
}; // ClassName ends with semi-colon
int main()
{
ClassName ObjectName; // Declare an object of class
ObjectName.DataMember.; // Accessing data member
ObjectName.MemberFunction(); // Accessing member function
return 0;
}
C++ Program
C++ Program Structure
Data encapsulation
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
 Binding (or wrapping) code and data
together into a single unit (called
class) are known as encapsulation.
• The data is not accessible to the
outside world, and only those
functions which are wrapped in the
class can access it.
• These functions provide the interface
between the objects data and the
program.
Data
Method
Method
Method
Class
Fig. 1.2.3 Concept of Encapsulation
Data Abstraction and Information Hiding
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
 Data Abstraction:
• Abstraction refers to the act of representing essential features without including the background
details or explanation.
• Classes use the concept of abstraction and are defined as a list of abstract attributes such as roll
number, name, and cost, and function operate on these attributes. They encapsulate all the
essential properties of the object that are to be created.
 Information Hiding:
• Functions provide the interface between the object’s data and the program. This insulation of the
data from direct access by the program is called data hiding or information hiding.
• The data member of member function of a class can be declared as public or private.
• If particular data attribute is declared as public then it is accessible to any other class. But if the
data member is declared as private then only the member function of that class can access the
data values. Another class cannot access these data values. This property is called data hiding.
Inheritance
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
 Inheritance is the process by which objects of one class acquired the properties of objects of
another classes.
 It provides the idea of reusability. This means that we can add additional features to an existing
class without modifying it.
 This is possible by deriving a new class from the existing one. The new class will have the
combined feature of both the classes.
#include<iostream>
Using namespace std;
class Parent /* Base Class or parent class or super class */
{
public:
int id_p;
};
class Child: public Parent /* Sub Class or Child class or derived class */
{
public:
int id_c;
};
int main()
{
child obj1; /* An object class child has all data members and member functions of class parent */
obj1.id_c = 7;
obj1.id_p = 1;
cout<<“Child id is”<<obj1.id_c<<endl;
cout<<“Child id is”<<obj1.id_p<<endl;
return 0;
}
Output:
Child id is 7
Parent id is 1
Polymorphism
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
 It means the ability to take more than one form.
 Suppose the word square has two meanings. You can find square of a number. Also you can
calculate area of a square. So, an operation may exhibit different behaviors in different instances.
 In c++, use operator overloading and function overriding to achieve polymorphism.
 Function overloading: It a single function name can be used to handle different number and
different types of argument.
 Polymorphism is extensively used in implementing inheritance.
Inheritance and Polymorphism Example
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Shape
Draw()
Circle
Draw()
Box
Draw()
Triangle
Draw()
Inheritance:
• Here the shape is a base class
from which the circle, box and
triangle are the derived classes.
• These derived classes inherit the
functionality Draw().
Polymorphism:
• Draw() to call is totally depend
upon the numbers of parameters
to functions
• If we are passing radius and center
coordinates then circle type of
Draw(Circle) should get called. If
we passing three sides parameters
then Draw(triangle) should get
called and so on.
Fig. 1.2.4 Example of inheritance and polymorphism
Dynamic Binding
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
 Dynamic binding is the method of linking procedure call with its code at the time of executing the
code. In other words, it occurs at runtime. Dynamic binding is also called late binding.
 Consider the procedure “draw” in fig. by inheritance, every object will have this procedure.
Its algorithm is, however, unique to each object and so the draw procedure will be redefined in each
class that defines the object. At run-time, the code matching the object under current reference will
be called.
Introduction to C++
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
 C++ was developed by Bjarne Stroustrup in the year 1983.
 It supports both procedural and object oriented.
 It supports inheritance, function overloading and operator overloading.
 It follows bottom-up approach.
C++ Headers
Class definition
Member function definition
Main function
Structure of a C++ program
 Header files in c++
#include<iostream.h> - To stored input output statements
# - preprocessor
include – keyword
io – Input and Output
stream – sequence of bytes
.h – header file
 Standard output stream (cout): Usually the standard output device is the display screen. The
C++ cout statement is the instance of the ostream class. It is used to produce output on the standard
output device which is usually the display screen. The data needed to be displayed on the screen is
inserted in the standard output stream (cout) using the insertion operator(<<).
 Standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin statement
is the instance of the class iostream and is used to read input from the standard input device which is
usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The
extraction operator extracts the data from the object cin which is entered using the keyboard.
 using namespace std means that we can use names for objects and variables from the standard library.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Simple C++ program
Following commands must be
executed on terminal window.
1.g++ -O FirstProg FirstProg.cpp
2../FirstProg
C++ Program:
FirstProg.cpp
//This Simple C++ program
//Simply prints “Hello World!”
message
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
Output : Hello World!
Program Explanation:
Line 1: The first two lines are the comments. It is non executable portion.
Line 2: #include <iostream> is a header file library that lets us work with input and output objects,
such as cout. Header files add functionality to C++ programs.
Line 3: using namespace std means that we can use names for objects and variables from the
standard library.
Line 4: A blank line. C++ ignores white space.
Line 5: Another thing that always appear in a C++ program, is int main(). This is called a function.
Any code inside its curly brackets {} will be executed.
Line 6: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to
output/print text. In our example it will output "Hello World".
Note: Every C++ statement ends with a semicolon ;.
Note: The body of int main() could also been written as:
int main ()
{
cout << "Hello World! ";
return 0;
}
Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.
Line 7: return 0 ends the main function.
Line 8: Do not forget to add the closing curly bracket } to actually end the main function
Identifiers in c++
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A C++ identifier is a name used to identify a variable, function, class,
module, or any other user-defined item.
• 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
• E.g. Mohd, zara, abc, move_name, a_123
myname50, _temp, j, a23b9, retVal
Comments in c++
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Program comments are explanatory statements that you can include in the C++ code that
you write and helps anyone reading it's source code
• All programming languages allow for some form of comments.
• C++ supports single-line and multi-line comments
• C++ comments start with /* and end with */.
• /* This is a comment */
• /*
C++ comments can also
* span multiple lines
*/
• // prints Hello World ---single line comment
Data types in c++
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
C++ Data
types
User-defined
type
structure
union
class
enum
Built-in
type
Integral
type
int
char
void
Floating
type
float
double
Derived
type
array
function
pointer
reference
Fig. 1.3.2 Hierarchy of C++ data types
Variables
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• In all programming languages, we need to use various variables to store various
information
• are nothing but reserved memory locations to store values
• to store information of various data types like character, wide character, integer, floating
point, double floating point, Boolean etc.
• Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory.
• Variable provides us with named storage that our programs can manipulate.
• The name of a variable can be composed of letters, digits, and the underscore character.
Local and global variables
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Local Variable
● Variables that are declared inside a function or block are local variables.
● They can be used only by statements that are inside that function or block of code.
● Local variables are not known to functions outside their own
• Global Variables
● Global variables are defined outside of all the functions, usually on top of the program
● The global variables will hold their value throughout the life-time of your program.
● A global variable can be accessed by any function
● Global variable is available for use throughout your entire program after its declaration
Variables
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
Variables
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
Function
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A function is a group of statements that together perform a task.
• 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.
• Syntax:
Declaration: return_type function_name(parameter_list) //formal parameter
e.g., int add(int a, int b)
Definition:
return_type function_name(parameter_list) //formal parameter
{
//body of function
}
e.g. int add(int a, int b)
{
int z= a+b;
return z;
}
Function
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Function call: function_name(parameter); //actual parameter
e.g. add(2,3);
• There are two ways to pas value or data to function:
1. Call by value
2. Call by reference
Call by value
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Original value is not modified
• If change the value of function
parameter, it is changed for
function only
• It will not change the value of
variable inside the caller method
such as main().
• Actual and formal arguments will be
created in different memory
location
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl
;
return 0;
}
void change(int data)
{
data = 5;
}
Output:
Value of the data is: 3
Call by reference
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• original value is modified because
here pass reference (address).
• address of the value is passed in
the function, so actual and formal
arguments share the same address
space
• Hence, value changed inside the
function, is reflected inside as well
as outside the function.
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
Output:
Value of x is: 100 Value of y is: 500
Return by reference
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Not only can you pass values by reference to
a function but you can also return a value by
reference.
• In program, the return type of
function test() is int&. Hence, this function returns
a reference of the variable num.
• The return statement is return num; Unlike return
by value, this statement doesn't return value
of num, instead it returns the variable itself
(address).
• So, when the variable is returned, it can be
assigned a value as done in test() = 5;
• This stores 5 to the variable num, which is
displayed onto the screen.
#include<iostream>
using namespace std;
// Global variable
int num;
// Function declaration
int& test();
int main()
{
test() = 5;
cout << num;
return 0;
}
int& test()
{
return num;
}
Output: 5
Inline function
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• Inline function use to reduce the
function call overhead.
• It is expanded in line when it is
invoked. i.e., the compiler replaces
the function call with corresponding
function code.
• The syntax for defining the function
inline is:
inline return-type function-
name(parameters)
{
// function code
}
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "n";
return 0;
}
Output: The cube of 3 is: 27
Inline function
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• Some of the situations where inline expansion may not work are:
• For functions returning values, if a loop, a switch, or a goto exists.
• For functions returning values, if return statement exists.
• If statement contain static variable.
• If inline functions are recursive.
Function with default arguments
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• It allows us to call a function without specifying all its arguments.
• In such cases, the function assign a default value to parameter which does
not have a matching argument in the function call.
• Default values are specified when the function is declared.
• Default arguments are useful in some situations when some arguments
always have same value.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
#include<iostream>
using namespace std;
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
/* Driver program to test above function*/
int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output:
25
50
80
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
•
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Function Overloading
 It is a concept in which one can use many functions having same function name but
can pass different number of parameters or different types of parameters.
 Rules for function overloading-
1. The overloaded functions may differ by number of parameters.
2. The overloaded functions may differ by data types.
3. The same function name is used for various instances of function call.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream.h>
using namespace std;
class Number
{
public:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
// function with same name but 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}
// function with same name and 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};
Output:
value of x is 7 value of x is 9.132 value of x and y is 85, 64
int main() {
Number obj1;
// Which function is called will
depend on the parameters passed
// The first 'func' is called
obj1.func(7);
// The second 'func' is called
obj1.func(9.132);
// The third 'func' is called
obj1.func(85,64);
return 0;
}
this pointer
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• Every object in c++ has access to its own address through an important
pointer called this pointer.
• Only member functions have a this pointer
• this is a keyword that refers to the current instances of a class.
• There can be 3 main usage of this keyword:
used to-
1. Pass current object as a parameter to another method.
2. Refers current class instance variable.
3. Declare indexers.
• this is a pointer that points to the object for which this function is called.
•
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include <iostream>
using namespace std;
class Test
{
int a,b;
public:
void show()
{
a=10;
b=20;
cout<<"object of address:"<<this<<endl;
cout<<"a="<<this->a<<endl;
cout<<"b="<<this->b;
}
};
int main()
{
Test t;
t.show();
return 0;
}
Output:
object of address:0x7ffd84be86d0
a=10
b=20
Dynamic initialization of variables
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• Value is being assigned to variable at runtime.
int a;
cout<<“Enter the value for a”;
cin>>a;
• The value of this variable can be altered every time the program is being run.
Memory management operators
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• Memory management is a process of managing memory, assigning the memory space to the
programs to improve overall system performance.
• Why memory management required?
• Array store the homogenous data, so most of time, memory allocated to the array at
the declaration time.
• Sometimes the situation arises when the exact memory is not determined until runtime.
• To avoid such a situation, we declare an array with maximum size, but some memory will
be unused.
• To avoid the wastage of memory, in c++ we use the new operator and in c we use
malloc(), calloc() to allocate the memory dynamically at the run time.
Memory management operators
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• In C language,
• malloc(), calloc() used to allocate memory dynamically run time.
• free() used to deallocate the dynamically allocated memory.
• In C++ language,
• new operator used to allocate memory dynamically run time.
• delete operator used to deallocate the dynamically allocated memory.
new operator
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• It is used to create the object
Syntax: pointer_variable = new data-type
Example,
int *p;
p = new int;
In the above example, 'p' is a pointer of type int.
• We can also assign the values by using new operator which can be done as follows:
Syntax: pointer_variable = new data-type(value);
Example,
int *p= new int(25);
• It is used to create a single dimensional array
Syntax: pointer-variable = new data-type[size];
Example,
int *a1 = new int[8];
• It is used to create memory space for any data-type or even user-defined data type such
as an array, structures, unions, etc.,
delete operator
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• • When memory is no longer required, then it needs to be deallocated so that the memory
can be used for another purpose.
• This can be achieved by using the delete operator, as shown below:
Syntax: delete pointer_variable;
Example,
delete p;
• The dynamically allocated array can also be removed from the memory space by using the
following
Syntax: delete [size] pointer_variable;
Operators in C++
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• • All C operators are valid in C++. In addition, C++ introduces some new operators are:
:: Scope resolution operator
::* Pointer-to-member declarator
->* Pointer-to-member operator
.* Pointer-to-member operator
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator
<< Insertion operator
>> Extraction operator
Member dereferencing Operators
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• • C++ permits-
• To define a class containing various types of data and functions as members.
• To access the class member through pointers.
• In order to achieve this, C++ provides a set of 3 pointer-to-member operators.
Operator Functions
::* To declare pointer to member of a class
* To access a member using object name and pointer to
that variable
->* To access a member using a pointer to the object and a
pointer to that member
Scope resolution operators
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• C and C++ are a block structured language.
• Blocks and scopes can be used in constructing programs.
• Same variable name can be used to have different meaning in different blocks.
• The scope of the variable extends from the point of its declaration till the end of block containing the
declaration.
• A variable declared inside a block is said to be local to that block.
{
int x=10;
}
{
int x=5;
}
Two declaration of x refers to two different memory
location containing different values
Statements in second block cannot refer to the variable
x declared in the first block and vice-versa.
Scope resolution operators
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
Blocks in c++ are often nested-
e.g.,
{
int x=10;
{
int x=1;
}
}
block 1 block 2
Scope resolution operators
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• Here, declaration in an inner block hides a declaration of the same variable in an outer block.
Therefore, each declaration of x causes it to refer to a different data object declared there in.
• In C, the global version of a variable can't be accessed from with in the inner block.
• C++ resolves this problem by introducing a new operator :: called the scope resolution operator. This
can be used to uncover a hidden variable.
• Syntax: : : variable–name;
• It is used for following purposes:
o To access a global variable when there is global variable with same name.
o To define function outside the class.
o To access class’s static variable.
o In case of multiple inheritance.
o For namespace
o Refer to class inside another class.
Scope resolution operators
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• #include<iostream>
using namespace std
int m=10; //global
int main()
{
int m=20; //m redeclared, local to main
{
int k=m;
int m=30; // declared again local to inner block
cout<<“We are in inner block n”;
cout<<“k = ”<< k << “n”;
cout<<“m =”<<m<<“n”;
cout<<“ ::m = ”<< ::m <<“n”;
}
cout<<“We are in outer block n”;
cout<<“m =”<<m<<“n”;
cout<<“ ::m = ”<< ::m <<“n”;
return 0;
}
Output:
We are in inner block
k = 20
m = 30
::m = 10
We are in outer block
m = 20
::m = 10
In the program, the variable m is declared at three
places, namely. Outside main() function , inside the
main(), and inside the inner block.
It is to noted ::m will always refers to the global m. In the
inner block, ::m refers to the value 10 and not 20.
Typecast operator
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• It is a mechanism which enables a variable of one datatype to be converted to another
datatype.
• Type of typecasting:
1. Implicit
2. Explicit
Implicit typecasting
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• • Conversion of data types without losing its original meaning.
• This type of typecasting essential when you want to change data types without
changing the significance of the values stored inside the variable.
• Don’t require any keyword or special statements.
• Converting smaller data type into larger data type is called as type promotion.
• Not Compatible data types-
• Float to integer
• Double to float with round up the digits.
• Long int to int will cause dropping of excess high order bits.
Implicit typecasting
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
#include<iostream>
using namespace std;
Int main()
{
short a=100; //initializing variable of short datatype
int b; //declaring variable of integer datatype
b=a; // implict type-casting
cout<<“a=”<<a;
cout<<“b=”<<b;
return 0;
}
Output:
a=100
b=100
Explicit typecasting
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• In implicit type casting, data type is converted automatically.
• There are some scenarios in which we may have to force type conversion.
• For e.g.,
int result;
int var1=10, var2=3;
result = var1/var2;
In this case, after division performed on variables var1 & var2 the result stored in
variable result will be in an integer.
Whenever this happens, the value store in the variable “result ” loses its meaning bez,
it doesn’t consider the fraction part which is normally obtained in division of two
numbers.
To force the type conversion in such situation we use explicit type casting.
Explicit typecasting
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• • C++ permits explicit type conversion of variable using type cast operator.
• Syntax:
• type-name (expression)
• Type-name is behaves as a function for converting values to a designated type.
• E.g., float (i);
Output:
var1=25
var2= 35.87
float to integer = 25
integer to float = 35
#include <iostream>
using namespace std;
int main()
{
int var1 =25;
float var2= 35.87;
cout<<"var1="<<var1;
cout<<"n var2="<<var2;
cout<<"n float to integer="<<float(var1);
cout<<"n integer to float="<<int(var2);
return 0;
}
Operator precedence
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Concept of precedence:
• if there are multiple operators in expression then all the operations are not
evaluated at a time. The operators with highest precedence evaluated first.
• for example, 4+5*8
• In above expression (5*8) is evaluated first, which comes out to be 40. Then we
can perform addition operation. Hence the answer is 44.
• Concept of associativity:
• operator associativity is the direction in which an expression is evaluated. The
direction can be from left to right or from right to left.
• The following table shows the precedence and associativity of various operators.
Operator Precedence
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
Operator Precedence
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
Operator Precedence
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
Operator Precedence
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Compile time- It is the time at which source code is converted into an executable code.
• Runtime – It is time at which the executable code started is running.
• Explanation: Compile and Execute C Program
Let us look at a simple code that would print the words "Hello World"-
Let us see how to save the source code in a file, and how to compile and run it.
Following are the simple steps -
• Open a text editor and add or write code in a text editor:-
#include<stdio.h>
int main()
{
printf("Hello World!!!");
return 0;
}
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
•
• Save the file as hello.c
• Open a terminal and go to the directory where you have saved the file.
• Type gcc hello.c 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 a.out executable file.
• Now, type ./a.out to execute your program.
• a.out is an executable file.
• While ./a.out is a terminal command to execute this exectable file.
• You will see the output "Hello World" printed on the screen.
Compile time
Runtime
Array
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Arrays are referred to as structured data types.
• An array is defined as finite ordered collection of homogenous data, stored in
contiguous memory locations.
1. finite means data range must be defined.
2. ordered means data must be stored in continuous memory addresses.
3. homogenous means data must be of similar data type.
• Example:
where arrays are used,
1. to store list of Employee or Student names,
2. to store marks of students,
3. to store list of numbers or characters etc.
Array
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
• Declaration:
data_type array_name[array_size];
Example:
int arr[10];
Here,
▪ int is the data type,
▪ arr is the name of the array and 10 is the size of array. It means array arr can only
contain 10 elements of int type.
▪ Index of an array starts from 0 to size-1 i.e first element of arr array will be stored
at arr[0] address and the last element will occupy arr[9].
Array
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Initialization of an Array:
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any
random value). An array can be initialized at either compile time or at runtime.
1. Compile time Array initialization
• Compile time initialization of array elements is same as ordinary variable initialization.
• The general form of initialization of array is,
Syntax:
data-type array-name[size] = { list of values };
Examples:
int marks[4]={ 67, 87, 56, 77 }; // integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization
int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error
When you will give more initializer(array elements) than the declared array size than the
compiler will give an error.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
2. Runtime Array initialization
An array can also be initialized at runtime using cin() function. This approach is usually used for
initializing large arrays, or to initialize arrays with user specified values.
#include <iostream>
using namespace std;
int main()
{
int arr[4]; //array declaration
int i;
cout<<"Enter array element:";
for(i = 0; i < 4; i++)
{
cin>>arr[i]; //Run time array initialization
}
cout<<"Array Elements are:";
for(i = 0; i < 4; i++)
{
cout<<"n" <<arr[i];
}
return 0;
}
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Array Elements Store in Memory:
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Accessing Array Elements:
Array elements are accessed by using an integer index. Array index starts with 0 and
goes till size of array minus 1.
Thank You….

More Related Content

What's hot

Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
daxesh chauhan
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 

What's hot (20)

C# language
C# languageC# language
C# language
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
CSharp.ppt
CSharp.pptCSharp.ppt
CSharp.ppt
 
C#.NET
C#.NETC#.NET
C#.NET
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Prgramming paradigms
Prgramming paradigmsPrgramming paradigms
Prgramming paradigms
 
Encapsulation in C++
Encapsulation in C++Encapsulation in C++
Encapsulation in C++
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
C/C++ History in few slides
C/C++ History in few slides C/C++ History in few slides
C/C++ History in few slides
 
Linker and Loader
Linker and Loader Linker and Loader
Linker and Loader
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Programming in c
Programming in cProgramming in c
Programming in c
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 

Similar to OOP Unit 1 - Foundation of Object- Oriented Programming

Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
farhan amjad
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
Asfand Hassan
 

Similar to OOP Unit 1 - Foundation of Object- Oriented Programming (20)

Oop in c++ lecture 1
Oop in c++  lecture 1Oop in c++  lecture 1
Oop in c++ lecture 1
 
chapter-6-oops.pdf
chapter-6-oops.pdfchapter-6-oops.pdf
chapter-6-oops.pdf
 
OOPM - Introduction.pptx
OOPM - Introduction.pptxOOPM - Introduction.pptx
OOPM - Introduction.pptx
 
Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - Introduction
 
OOP-1.pptx
OOP-1.pptxOOP-1.pptx
OOP-1.pptx
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
C++ notes.pdf
C++ notes.pdfC++ notes.pdf
C++ notes.pdf
 
OOP ppt.pdf
OOP ppt.pdfOOP ppt.pdf
OOP ppt.pdf
 
Bca 2nd sem u-1 iintroduction
Bca 2nd sem u-1 iintroductionBca 2nd sem u-1 iintroduction
Bca 2nd sem u-1 iintroduction
 
Abhiram
AbhiramAbhiram
Abhiram
 
Unit 1 introduction to c++.pptx
Unit 1 introduction to c++.pptxUnit 1 introduction to c++.pptx
Unit 1 introduction to c++.pptx
 
Mca 2 sem u-1 iintroduction
Mca 2 sem u-1 iintroductionMca 2 sem u-1 iintroduction
Mca 2 sem u-1 iintroduction
 
Oop basic overview
Oop basic overviewOop basic overview
Oop basic overview
 
Need of OOPs and Programming,pop vs oop
Need of OOPs and Programming,pop vs oopNeed of OOPs and Programming,pop vs oop
Need of OOPs and Programming,pop vs oop
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 

OOP Unit 1 - Foundation of Object- Oriented Programming

  • 1. FOUNDATION OF OBJECT-ORIENTED PROGRAMMING By- Ms. Dipali K. Pawar ME(Comp), BE(Comp) Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming Unit I
  • 2. Contents • Introduction to procedural, modular, object-oriented and generic programming techniques • Limitations of procedural programming • Need of object-oriented programming • fundamentals of object-oriented programming: • objects, classes, data members, methods, messages, data encapsulation, data abstraction and information hiding, inheritance, polymorphism. • Inline functions • Function overloading • call by value and call by reference, return by reference, Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 3. Survey of Programming Techniques Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)  The development of software product using well-defined scientific principles, methods and procedures is called as Software engineering.  For developing software, we have first made design for software.  Software designing is one of the phases of software development cycle.  There are some approaches for software designing process.
  • 4. Survey of Programming Techniques Unstructured Programming Procedural Programming Modular Programming Object-oriented programming Generic programming Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 5. Unstructured Programming  Only one program i.e., main program  All the sequences of commands or statements in one programs called main program  Hole program must be written in single continuous way; there is no stop or broken block.  Example: Assembly language, Old basic Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Fig. 1.1.1 Typical structure of unstructured program
  • 6. Structured Programming  Also called as Procedural programming(POP)  For each task procedure is created called as function  The procedures are called from main program  Example: COBOL, FORTRAN, C Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Fig. 1.1.2 Typical structure of structured programs
  • 7. Modular Programming  Procedures with some common functionality are grouped together into separate modules  Program is categorized into several smaller modules  Each module can have its own data  Example: C, C++ Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Fig. 1.1.3 Typical structure of modular programs
  • 8. Object Oriented Programming(OOP)  Works on objects which is considered smallest unit of the object-oriented languages  Focuses more on data rather than procedures  Data structures are designed such that they characterize the objects  Example: C++, java Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Fig. 1.1.4 Organization of data and functions in OOP
  • 9. Example of addition of two numbers Unstructured Programming Structured Programming Object Oriented Programming #include<iostream> using namespace std; int main() { int a,b,c; clrscr(); cout << "Enter the first number"; cin >> a; cout << "Enter the second number"; cin >> b; c=a+b; cout << "The sum is:" << c; return 0 } #include<iostream> using namespace std; int add(int,int); void main() { int a,b,c; clrscr(); cout << "Enter the first number"; cin >> a; cout << "Enter the second number"; cin >> b; c=add(a,b); cout<<"The sum is:" << c; getch(); } int add(int x,int y) { int z=x+y; return z; } #include<iostream > using namespace std; class Addition { int a,b,c; public: void read() { cin >> a; cin >> b; } void add() { c=a+b; } void display() { cout << "The sum is:" << c; } }; void main() { Addition obj; cout << "Enter the numbers"; obj.read(); obj.add(); obj.display(); getch(); } Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 10. Generic Programming  Refers to writing code that will work for many types of data.  It is implemented to increase the efficiency of the code.  It enables the programmer to write a general algorithm which will work with all data types.  It eliminates the need to create different algorithms if the data type is an integer, string or a character.  Generics can be implemented in C++ using Templates. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 11. Generic Programming using Template Example in C++  A generic function that can be used for different data types. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) #include <iostream> using namespace std; // One function works for all data types. // This would work even for user defined types // if operator '>' is overloaded template <typename T> T myMax(T x, T y) { return (x > y) ? x : y; } int main() { // Call myMax for int cout << myMax<int>(3, 7) << endl; // call myMax for double cout << myMax<double>(3.0, 7.0) << endl; // call myMax for char cout << myMax<char>('g', 'e') << endl; return 0; } Output: 7 7.0 g int myMax(int x, int y) { return (x > y) ? x : y; } double myMax(double x, double y) { return (x > y) ? x : y; } char myMax(char x, char y) { return (x > y) ? x : y; }
  • 12. Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Department of E&TC Engineering, MCERC, Nashik Feature Procedure oriented Programming Object oriented Programming Divided Into In POP Program is divided into small parts called functions. In OOP, program is divided into parts called objects. Importance In POP, Importance is not given to data but to functions as well as sequence of actions to be done. In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. Approach POP follows Top-Down approach. OOP follows Bottom-Up approach. Access Specifiers POP does not have any access specifier OOP has access specifiers named Public, Private, Protected, etc. Data Moving In POP, Data can move freely from function to function in the system. In OOP, objects can move and communicate with each other through member functions. Expansion To add new data and function in POP is not so easy. OOP provides an easy way to add new data and function. Data Access In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system. In OOP, data can not move easily from function to function, it can be kept public or private so we can control the access of data. Data Hiding POP does not have any proper way for hiding data, so it is less secure. OOP provides Data Hiding so provides more security. Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. Examples Examples: C, VB, FORTRAN, Pascal. Examples: C++, JAVA, VB.NET, C#.NET.
  • 13. Limitations of Procedural Programming  Poor real-world model.  No importance to data.  No privacy.  No true reuse.  Functions and data should be treated equally. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 14. Features of Object-Oriented Programming 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. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 15. Need of Object-Oriented Programming • To overcome the drawbacks of the POP. • Code Reuse and Recycling: objects are created for object-oriented programs can easily be reused in other programs. • Design benefits: Large programs are difficult to write. Object oriented programs force designers to go through an extensive planning phase, which makes for better designs with less flaws. In addition, once a program reaches a certain size. Object oriented programs are actually easier to program than non-object-oriented once. • Software maintenance: Programs are not disposable. An object-oriented program is much easier to modify and maintain than a non-object-oriented program. So, although a lot of work is spent before the program is written, less work is needed to maintain it over time. • Simplicity: The objects in case of OOP are close to the real-world objects, so the complexity of the program is reduced making the program structure very simple and clear. For example by looking at the class Mobile_phone, you can simply identify with the properties and behavior of an actual mobile phone. This makes the class Mobile_phone very simple and easy to understand. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 16. Fundamentals of Object-Oriented Programming Languages Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Objects • Classes • Data members • Methods and Messages • Data encapsulation • Data abstraction and information hiding • Inheritance • Polymorphism • Dynamic Binding
  • 17. Classes  Class is a template/blue-print for real-world entities from which objects are created.  It is a group of similar objects.  It is a logical entity.  Classes define states as instance variables and behaviors as instance methods.  Instance variables are also known as member variable  It doesn’t allocated memory when it is created.  Class is declared once.  Classes declared using class keyword Syntax: class ClassName{} E.g., class Student{}; Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Properties Behavior • Color • Cost • Battery Life • Make Calls • Watches Videos • Play Games Fig. 1.2.1 Example of Mobile as Class
  • 18. Objects  Objects are specific instances of a class.  It is an entity that has states and behaviors.  State tells how the object looks or what properties it has.  Behavior tells what the object does.  Object is a physical entity.  Object is created many times as per requirement.  Object allocates memory when it is created.  Objects created as: Syntax: ClassName ObjectName; E.g., Student stud; Student stud1, stud2; Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 19. Objects Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Fig. 1.2.2 Example of Mobile as Class and their different brands of mobile as objects
  • 20. Data Members  The data members are variables that are declared within the class.  These members are declared along with data types.  The access specifier to these members can be public, private or protected.  These data members can be accessible by main() function using the object of a class. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 21. Method and Message Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)  Object is an instances of a class. Every object consists of both data attributes and methods. The data attributes of every object are manipulated by the methods. These objects in the program communicate with each other by sending messages.  Message passing is the method of exchanging messages among objects.  A Message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in the receiving object that generates the desired results.  Message passing involves specifying the name of object, the name of the function (message) and the information to be sent.  Example: Employee.Salary(name); object message information
  • 22. #include <iostream.h> using namespace std; class Student { // Access specifier public: // Data Members/Properties/Attributes/instance variable string name; // Member Functions/operations/methods/instance method void printname() { cout << “Student name is: " << name; } }; int main() { // Declare an object of class Student Student stud; // accessing data member stud. name = "ABC"; // accessing member function stud.printname(); return 0; } class ClassName { Access Specifiers; //public, private, protected Data Members/ Instance Variable/ Properties/ Attributes; //variables to be used Member functions()/ Instance Methods()/ Operations()/ Methods() //Methods to access data methods { //function body } }; // ClassName ends with semi-colon int main() { ClassName ObjectName; // Declare an object of class ObjectName.DataMember.; // Accessing data member ObjectName.MemberFunction(); // Accessing member function return 0; } C++ Program C++ Program Structure
  • 23. Data encapsulation Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)  Binding (or wrapping) code and data together into a single unit (called class) are known as encapsulation. • The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. • These functions provide the interface between the objects data and the program. Data Method Method Method Class Fig. 1.2.3 Concept of Encapsulation
  • 24. Data Abstraction and Information Hiding Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)  Data Abstraction: • Abstraction refers to the act of representing essential features without including the background details or explanation. • Classes use the concept of abstraction and are defined as a list of abstract attributes such as roll number, name, and cost, and function operate on these attributes. They encapsulate all the essential properties of the object that are to be created.  Information Hiding: • Functions provide the interface between the object’s data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding. • The data member of member function of a class can be declared as public or private. • If particular data attribute is declared as public then it is accessible to any other class. But if the data member is declared as private then only the member function of that class can access the data values. Another class cannot access these data values. This property is called data hiding.
  • 25. Inheritance Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)  Inheritance is the process by which objects of one class acquired the properties of objects of another classes.  It provides the idea of reusability. This means that we can add additional features to an existing class without modifying it.  This is possible by deriving a new class from the existing one. The new class will have the combined feature of both the classes.
  • 26. #include<iostream> Using namespace std; class Parent /* Base Class or parent class or super class */ { public: int id_p; }; class Child: public Parent /* Sub Class or Child class or derived class */ { public: int id_c; }; int main() { child obj1; /* An object class child has all data members and member functions of class parent */ obj1.id_c = 7; obj1.id_p = 1; cout<<“Child id is”<<obj1.id_c<<endl; cout<<“Child id is”<<obj1.id_p<<endl; return 0; } Output: Child id is 7 Parent id is 1
  • 27. Polymorphism Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)  It means the ability to take more than one form.  Suppose the word square has two meanings. You can find square of a number. Also you can calculate area of a square. So, an operation may exhibit different behaviors in different instances.  In c++, use operator overloading and function overriding to achieve polymorphism.  Function overloading: It a single function name can be used to handle different number and different types of argument.  Polymorphism is extensively used in implementing inheritance.
  • 28. Inheritance and Polymorphism Example Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Shape Draw() Circle Draw() Box Draw() Triangle Draw() Inheritance: • Here the shape is a base class from which the circle, box and triangle are the derived classes. • These derived classes inherit the functionality Draw(). Polymorphism: • Draw() to call is totally depend upon the numbers of parameters to functions • If we are passing radius and center coordinates then circle type of Draw(Circle) should get called. If we passing three sides parameters then Draw(triangle) should get called and so on. Fig. 1.2.4 Example of inheritance and polymorphism
  • 29. Dynamic Binding Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)  Dynamic binding is the method of linking procedure call with its code at the time of executing the code. In other words, it occurs at runtime. Dynamic binding is also called late binding.  Consider the procedure “draw” in fig. by inheritance, every object will have this procedure. Its algorithm is, however, unique to each object and so the draw procedure will be redefined in each class that defines the object. At run-time, the code matching the object under current reference will be called.
  • 30. Introduction to C++ Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)  C++ was developed by Bjarne Stroustrup in the year 1983.  It supports both procedural and object oriented.  It supports inheritance, function overloading and operator overloading.  It follows bottom-up approach. C++ Headers Class definition Member function definition Main function Structure of a C++ program
  • 31.  Header files in c++ #include<iostream.h> - To stored input output statements # - preprocessor include – keyword io – Input and Output stream – sequence of bytes .h – header file  Standard output stream (cout): Usually the standard output device is the display screen. The C++ cout statement is the instance of the ostream class. It is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<).  Standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin statement is the instance of the class iostream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.  using namespace std means that we can use names for objects and variables from the standard library. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 32. Simple C++ program Following commands must be executed on terminal window. 1.g++ -O FirstProg FirstProg.cpp 2../FirstProg C++ Program: FirstProg.cpp //This Simple C++ program //Simply prints “Hello World!” message #include <iostream> using namespace std; int main() { cout << "Hello World!"; return 0; } Output : Hello World! Program Explanation: Line 1: The first two lines are the comments. It is non executable portion. Line 2: #include <iostream> is a header file library that lets us work with input and output objects, such as cout. Header files add functionality to C++ programs. Line 3: using namespace std means that we can use names for objects and variables from the standard library. Line 4: A blank line. C++ ignores white space. Line 5: Another thing that always appear in a C++ program, is int main(). This is called a function. Any code inside its curly brackets {} will be executed. Line 6: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to output/print text. In our example it will output "Hello World". Note: Every C++ statement ends with a semicolon ;. Note: The body of int main() could also been written as: int main () { cout << "Hello World! "; return 0; } Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable. Line 7: return 0 ends the main function. Line 8: Do not forget to add the closing curly bracket } to actually end the main function
  • 33. Identifiers in c++ Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. • 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 • E.g. Mohd, zara, abc, move_name, a_123 myname50, _temp, j, a23b9, retVal
  • 34.
  • 35. Comments in c++ Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Program comments are explanatory statements that you can include in the C++ code that you write and helps anyone reading it's source code • All programming languages allow for some form of comments. • C++ supports single-line and multi-line comments • C++ comments start with /* and end with */. • /* This is a comment */ • /* C++ comments can also * span multiple lines */ • // prints Hello World ---single line comment
  • 36. Data types in c++ Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) C++ Data types User-defined type structure union class enum Built-in type Integral type int char void Floating type float double Derived type array function pointer reference Fig. 1.3.2 Hierarchy of C++ data types
  • 37.
  • 38.
  • 39. Variables Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • In all programming languages, we need to use various variables to store various information • are nothing but reserved memory locations to store values • to store information of various data types like character, wide character, integer, floating point, double floating point, Boolean etc. • Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. • Variable provides us with named storage that our programs can manipulate. • The name of a variable can be composed of letters, digits, and the underscore character.
  • 40. Local and global variables Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Local Variable ● Variables that are declared inside a function or block are local variables. ● They can be used only by statements that are inside that function or block of code. ● Local variables are not known to functions outside their own • Global Variables ● Global variables are defined outside of all the functions, usually on top of the program ● The global variables will hold their value throughout the life-time of your program. ● A global variable can be accessed by any function ● Global variable is available for use throughout your entire program after its declaration
  • 41. Variables Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) #include <iostream> using namespace std; // Global variable declaration: int g = 20; int main () { // Local variable declaration: int g = 10; cout << g; return 0; }
  • 42. Variables Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) #include <iostream> using namespace std; // Global variable declaration: int g = 20; int main () { // Local variable declaration: int g = 10; cout << g; return 0; }
  • 43. Function Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • A function is a group of statements that together perform a task. • 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. • Syntax: Declaration: return_type function_name(parameter_list) //formal parameter e.g., int add(int a, int b) Definition: return_type function_name(parameter_list) //formal parameter { //body of function } e.g. int add(int a, int b) { int z= a+b; return z; }
  • 44. Function Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Function call: function_name(parameter); //actual parameter e.g. add(2,3); • There are two ways to pas value or data to function: 1. Call by value 2. Call by reference
  • 45. Call by value Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Original value is not modified • If change the value of function parameter, it is changed for function only • It will not change the value of variable inside the caller method such as main(). • Actual and formal arguments will be created in different memory location #include <iostream> using namespace std; void change(int data); int main() { int data = 3; change(data); cout << "Value of the data is: " << data<< endl ; return 0; } void change(int data) { data = 5; } Output: Value of the data is: 3
  • 46. Call by reference Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • original value is modified because here pass reference (address). • address of the value is passed in the function, so actual and formal arguments share the same address space • Hence, value changed inside the function, is reflected inside as well as outside the function. #include<iostream> using namespace std; void swap(int *x, int *y) { int swap; swap=*x; *x=*y; *y=swap; } int main() { int x=500, y=100; swap(&x, &y); // passing value to function cout<<"Value of x is: "<<x<<endl; cout<<"Value of y is: "<<y<<endl; return 0; } Output: Value of x is: 100 Value of y is: 500
  • 47. Return by reference Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Not only can you pass values by reference to a function but you can also return a value by reference. • In program, the return type of function test() is int&. Hence, this function returns a reference of the variable num. • The return statement is return num; Unlike return by value, this statement doesn't return value of num, instead it returns the variable itself (address). • So, when the variable is returned, it can be assigned a value as done in test() = 5; • This stores 5 to the variable num, which is displayed onto the screen. #include<iostream> using namespace std; // Global variable int num; // Function declaration int& test(); int main() { test() = 5; cout << num; return 0; } int& test() { return num; } Output: 5
  • 48. Inline function Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • Inline function use to reduce the function call overhead. • It is expanded in line when it is invoked. i.e., the compiler replaces the function call with corresponding function code. • The syntax for defining the function inline is: inline return-type function- name(parameters) { // function code } #include <iostream> using namespace std; inline int cube(int s) { return s*s*s; } int main() { cout << "The cube of 3 is: " << cube(3) << "n"; return 0; } Output: The cube of 3 is: 27
  • 49. Inline function Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • Some of the situations where inline expansion may not work are: • For functions returning values, if a loop, a switch, or a goto exists. • For functions returning values, if return statement exists. • If statement contain static variable. • If inline functions are recursive.
  • 50. Function with default arguments Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • It allows us to call a function without specifying all its arguments. • In such cases, the function assign a default value to parameter which does not have a matching argument in the function call. • Default values are specified when the function is declared. • Default arguments are useful in some situations when some arguments always have same value.
  • 51. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • #include<iostream> using namespace std; // A function with default arguments, it can be called with // 2 arguments or 3 arguments or 4 arguments. int sum(int x, int y, int z=0, int w=0) { return (x + y + z + w); } /* Driver program to test above function*/ int main() { cout << sum(10, 15) << endl; cout << sum(10, 15, 25) << endl; cout << sum(10, 15, 25, 30) << endl; return 0; } Output: 25 50 80
  • 52. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) •
  • 53. • Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 54. Function Overloading  It is a concept in which one can use many functions having same function name but can pass different number of parameters or different types of parameters.  Rules for function overloading- 1. The overloaded functions may differ by number of parameters. 2. The overloaded functions may differ by data types. 3. The same function name is used for various instances of function call. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp)
  • 55. #include<iostream.h> using namespace std; class Number { public: // function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // function with same name but 1 double parameter void func(double x) { cout << "value of x is " << x << endl; } // function with same name and 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; Output: value of x is 7 value of x is 9.132 value of x and y is 85, 64 int main() { Number obj1; // Which function is called will depend on the parameters passed // The first 'func' is called obj1.func(7); // The second 'func' is called obj1.func(9.132); // The third 'func' is called obj1.func(85,64); return 0; }
  • 56. this pointer Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • Every object in c++ has access to its own address through an important pointer called this pointer. • Only member functions have a this pointer • this is a keyword that refers to the current instances of a class. • There can be 3 main usage of this keyword: used to- 1. Pass current object as a parameter to another method. 2. Refers current class instance variable. 3. Declare indexers. • this is a pointer that points to the object for which this function is called.
  • 57. • Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) #include <iostream> using namespace std; class Test { int a,b; public: void show() { a=10; b=20; cout<<"object of address:"<<this<<endl; cout<<"a="<<this->a<<endl; cout<<"b="<<this->b; } }; int main() { Test t; t.show(); return 0; } Output: object of address:0x7ffd84be86d0 a=10 b=20
  • 58. Dynamic initialization of variables Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • Value is being assigned to variable at runtime. int a; cout<<“Enter the value for a”; cin>>a; • The value of this variable can be altered every time the program is being run.
  • 59. Memory management operators Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • Memory management is a process of managing memory, assigning the memory space to the programs to improve overall system performance. • Why memory management required? • Array store the homogenous data, so most of time, memory allocated to the array at the declaration time. • Sometimes the situation arises when the exact memory is not determined until runtime. • To avoid such a situation, we declare an array with maximum size, but some memory will be unused. • To avoid the wastage of memory, in c++ we use the new operator and in c we use malloc(), calloc() to allocate the memory dynamically at the run time.
  • 60. Memory management operators Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • In C language, • malloc(), calloc() used to allocate memory dynamically run time. • free() used to deallocate the dynamically allocated memory. • In C++ language, • new operator used to allocate memory dynamically run time. • delete operator used to deallocate the dynamically allocated memory.
  • 61. new operator Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • It is used to create the object Syntax: pointer_variable = new data-type Example, int *p; p = new int; In the above example, 'p' is a pointer of type int. • We can also assign the values by using new operator which can be done as follows: Syntax: pointer_variable = new data-type(value); Example, int *p= new int(25); • It is used to create a single dimensional array Syntax: pointer-variable = new data-type[size]; Example, int *a1 = new int[8]; • It is used to create memory space for any data-type or even user-defined data type such as an array, structures, unions, etc.,
  • 62. delete operator Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • When memory is no longer required, then it needs to be deallocated so that the memory can be used for another purpose. • This can be achieved by using the delete operator, as shown below: Syntax: delete pointer_variable; Example, delete p; • The dynamically allocated array can also be removed from the memory space by using the following Syntax: delete [size] pointer_variable;
  • 63. Operators in C++ Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • All C operators are valid in C++. In addition, C++ introduces some new operators are: :: Scope resolution operator ::* Pointer-to-member declarator ->* Pointer-to-member operator .* Pointer-to-member operator delete Memory release operator endl Line feed operator new Memory allocation operator setw Field width operator << Insertion operator >> Extraction operator
  • 64. Member dereferencing Operators Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • C++ permits- • To define a class containing various types of data and functions as members. • To access the class member through pointers. • In order to achieve this, C++ provides a set of 3 pointer-to-member operators. Operator Functions ::* To declare pointer to member of a class * To access a member using object name and pointer to that variable ->* To access a member using a pointer to the object and a pointer to that member
  • 65. Scope resolution operators Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • C and C++ are a block structured language. • Blocks and scopes can be used in constructing programs. • Same variable name can be used to have different meaning in different blocks. • The scope of the variable extends from the point of its declaration till the end of block containing the declaration. • A variable declared inside a block is said to be local to that block. { int x=10; } { int x=5; } Two declaration of x refers to two different memory location containing different values Statements in second block cannot refer to the variable x declared in the first block and vice-versa.
  • 66. Scope resolution operators Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Blocks in c++ are often nested- e.g., { int x=10; { int x=1; } } block 1 block 2
  • 67. Scope resolution operators Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • Here, declaration in an inner block hides a declaration of the same variable in an outer block. Therefore, each declaration of x causes it to refer to a different data object declared there in. • In C, the global version of a variable can't be accessed from with in the inner block. • C++ resolves this problem by introducing a new operator :: called the scope resolution operator. This can be used to uncover a hidden variable. • Syntax: : : variable–name; • It is used for following purposes: o To access a global variable when there is global variable with same name. o To define function outside the class. o To access class’s static variable. o In case of multiple inheritance. o For namespace o Refer to class inside another class.
  • 68. Scope resolution operators Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • #include<iostream> using namespace std int m=10; //global int main() { int m=20; //m redeclared, local to main { int k=m; int m=30; // declared again local to inner block cout<<“We are in inner block n”; cout<<“k = ”<< k << “n”; cout<<“m =”<<m<<“n”; cout<<“ ::m = ”<< ::m <<“n”; } cout<<“We are in outer block n”; cout<<“m =”<<m<<“n”; cout<<“ ::m = ”<< ::m <<“n”; return 0; } Output: We are in inner block k = 20 m = 30 ::m = 10 We are in outer block m = 20 ::m = 10 In the program, the variable m is declared at three places, namely. Outside main() function , inside the main(), and inside the inner block. It is to noted ::m will always refers to the global m. In the inner block, ::m refers to the value 10 and not 20.
  • 69. Typecast operator Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • It is a mechanism which enables a variable of one datatype to be converted to another datatype. • Type of typecasting: 1. Implicit 2. Explicit
  • 70. Implicit typecasting Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • Conversion of data types without losing its original meaning. • This type of typecasting essential when you want to change data types without changing the significance of the values stored inside the variable. • Don’t require any keyword or special statements. • Converting smaller data type into larger data type is called as type promotion. • Not Compatible data types- • Float to integer • Double to float with round up the digits. • Long int to int will cause dropping of excess high order bits.
  • 71. Implicit typecasting Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • #include<iostream> using namespace std; Int main() { short a=100; //initializing variable of short datatype int b; //declaring variable of integer datatype b=a; // implict type-casting cout<<“a=”<<a; cout<<“b=”<<b; return 0; } Output: a=100 b=100
  • 72. Explicit typecasting Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • In implicit type casting, data type is converted automatically. • There are some scenarios in which we may have to force type conversion. • For e.g., int result; int var1=10, var2=3; result = var1/var2; In this case, after division performed on variables var1 & var2 the result stored in variable result will be in an integer. Whenever this happens, the value store in the variable “result ” loses its meaning bez, it doesn’t consider the fraction part which is normally obtained in division of two numbers. To force the type conversion in such situation we use explicit type casting.
  • 73. Explicit typecasting Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • C++ permits explicit type conversion of variable using type cast operator. • Syntax: • type-name (expression) • Type-name is behaves as a function for converting values to a designated type. • E.g., float (i); Output: var1=25 var2= 35.87 float to integer = 25 integer to float = 35 #include <iostream> using namespace std; int main() { int var1 =25; float var2= 35.87; cout<<"var1="<<var1; cout<<"n var2="<<var2; cout<<"n float to integer="<<float(var1); cout<<"n integer to float="<<int(var2); return 0; }
  • 74. Operator precedence Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Concept of precedence: • if there are multiple operators in expression then all the operations are not evaluated at a time. The operators with highest precedence evaluated first. • for example, 4+5*8 • In above expression (5*8) is evaluated first, which comes out to be 40. Then we can perform addition operation. Hence the answer is 44. • Concept of associativity: • operator associativity is the direction in which an expression is evaluated. The direction can be from left to right or from right to left. • The following table shows the precedence and associativity of various operators.
  • 75. Operator Precedence Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) •
  • 76. Operator Precedence Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) •
  • 77. Operator Precedence Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) •
  • 78. Operator Precedence Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) •
  • 79. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Compile time- It is the time at which source code is converted into an executable code. • Runtime – It is time at which the executable code started is running. • Explanation: Compile and Execute C Program Let us look at a simple code that would print the words "Hello World"- Let us see how to save the source code in a file, and how to compile and run it. Following are the simple steps - • Open a text editor and add or write code in a text editor:- #include<stdio.h> int main() { printf("Hello World!!!"); return 0; }
  • 80. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • • Save the file as hello.c • Open a terminal and go to the directory where you have saved the file. • Type gcc hello.c 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 a.out executable file. • Now, type ./a.out to execute your program. • a.out is an executable file. • While ./a.out is a terminal command to execute this exectable file. • You will see the output "Hello World" printed on the screen. Compile time Runtime
  • 81. Array Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Arrays are referred to as structured data types. • An array is defined as finite ordered collection of homogenous data, stored in contiguous memory locations. 1. finite means data range must be defined. 2. ordered means data must be stored in continuous memory addresses. 3. homogenous means data must be of similar data type. • Example: where arrays are used, 1. to store list of Employee or Student names, 2. to store marks of students, 3. to store list of numbers or characters etc.
  • 82. Array Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • The array is the simplest data structure where each data element can be randomly accessed by using its index number. • Declaration: data_type array_name[array_size]; Example: int arr[10]; Here, ▪ int is the data type, ▪ arr is the name of the array and 10 is the size of array. It means array arr can only contain 10 elements of int type. ▪ Index of an array starts from 0 to size-1 i.e first element of arr array will be stored at arr[0] address and the last element will occupy arr[9].
  • 83. Array Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) • Initialization of an Array: After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be initialized at either compile time or at runtime. 1. Compile time Array initialization • Compile time initialization of array elements is same as ordinary variable initialization. • The general form of initialization of array is, Syntax: data-type array-name[size] = { list of values }; Examples: int marks[4]={ 67, 87, 56, 77 }; // integer array initialization float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error When you will give more initializer(array elements) than the declared array size than the compiler will give an error.
  • 84. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) 2. Runtime Array initialization An array can also be initialized at runtime using cin() function. This approach is usually used for initializing large arrays, or to initialize arrays with user specified values. #include <iostream> using namespace std; int main() { int arr[4]; //array declaration int i; cout<<"Enter array element:"; for(i = 0; i < 4; i++) { cin>>arr[i]; //Run time array initialization } cout<<"Array Elements are:"; for(i = 0; i < 4; i++) { cout<<"n" <<arr[i]; } return 0; }
  • 85. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Array Elements Store in Memory:
  • 86. Department of E&TC Engineering, MCERC, Nashik Object Oriented Programming By- Ms. Dipali K. Pawar ME(Comp) , BE(Comp) Accessing Array Elements: Array elements are accessed by using an integer index. Array index starts with 0 and goes till size of array minus 1.

Editor's Notes

  1. NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image.