Download OOP-unit1 Fundamental of Object -Oriented Programming

Document related concepts
no text concepts found
Transcript
Department of E&TC Engineering, MCERC, Nashik
Unit I
FOUNDATION OF
OBJECTORIENTED
PROGRAMMING
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp), BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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,
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Survey of Programming Techniques
 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Survey of Programming Techniques
Unstructured Programming
Procedural Programming
Modular Programming
Object-oriented programming
Generic programming
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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
Fig. 1.1.1 Typical structure of unstructured program
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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
Fig. 1.1.2 Typical structure of structured programs
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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++
Fig. 1.1.3 Typical structure of modular programs
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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
Fig. 1.1.4 Organization of data and functions in OOP
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Example of addition of two numbers
Unstructured 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
}
Structured Programming
#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;
}
Object Oriented Programming
Object Oriented Programming
#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();
}
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Generic Programming using Template Example in C++
 A generic function that can be used for different data types.
#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;
}
Object Oriented Programming
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;
}
Output:
7
7.0
g
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.
Importance
In POP, Importance is not given to data but to functions as well as In OOP, Importance is given to the data rather than procedures or
functions because it works as a real world.
sequence of actions to be done.
Approach
Access Specifiers
Data Moving
In OOP, program is divided into parts called objects.
POP follows Top-Down approach.
OOP follows Bottom-Up approach.
POP does not have any access specifier
OOP has access specifiers named Public, Private, Protected, etc.
In POP, Data can move freely from function to function in the In OOP, objects can move and communicate with each other
system.
through member functions.
To add new data and function in POP is not so easy.
OOP provides an easy way to add new data and function.
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: C, VB, FORTRAN, Pascal.
Examples: C++, JAVA, VB.NET, C#.NET.
Expansion
Data Access
Examples
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Limitations of Procedural Programming
 Poor real-world model.
 No importance to data.
 No privacy.
 No true reuse.
 Functions and data should be treated equally.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Fundamentals of Object-Oriented Programming
Languages
•
•
•
•
•
•
•
•
•
Objects
Classes
Data members
Methods and Messages
Data encapsulation
Data abstraction and information hiding
Inheritance
Polymorphism
Dynamic Binding
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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.
Properties
• Color
• Cost
• Battery Life
Behavior
• Make Calls
• Watches
Videos
• Play Games
 Classes declared using class keyword
Syntax: class ClassName{}
Fig. 1.2.1 Example of Mobile as Class
E.g., class Student{};
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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;
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Objects
Fig. 1.2.2 Example of Mobile as Class and their different brands of mobile as objects
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Method and Message
 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
information
message
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
C++ Program Structure
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
#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;
}
Department of E&TC Engineering, MCERC, Nashik
Data encapsulation
 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.
Class
Data
Method
Method
Method
Fig. 1.2.3 Concept of Encapsulation
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Data Abstraction and Information Hiding
 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Inheritance
 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
Using namespace std;
class Parent
/* Base Class or parent class or super class */
{
public:
int id_p;
};
class Child: public Parent
{
public:
int id_c;
};
Output:
Child id is 7
Parent id is 1
/* Sub Class or Child class or derived class */
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;
}
Department of E&TC Engineering, MCERC, Nashik
Polymorphism
 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Inheritance and Polymorphism Example
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().
Shape
Draw()
Circle
Box
Triangle
Draw()
Draw()
Draw()
Fig. 1.2.4 Example of inheritance and polymorphism
Object Oriented Programming
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.
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Dynamic Binding
 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Introduction to C++
 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
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Simple C++ program
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!
Following commands must be
executed on terminal window.
1.g++ -O FirstProg
FirstProg.cpp
2../FirstProg
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
Department of E&TC Engineering, MCERC, Nashik
Identifiers in c++
•
•
•
•
•
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
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Comments in c++
•
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
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Data types in c++
C++ Data
types
Userdefined type
Built-in
type
Integral
type
structure
void
Derived
type
Floating
type
array
union
int
float
function
class
char
double
pointer
enum
reference
Fig. 1.3.2 Hierarchy of C++ data types
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Variables
•
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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Local and global variables
•
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
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Variables
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Variables
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Function
•
•
•
•
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;
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Function
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
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Call by value
• 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
Object Oriented Programming
#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
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Call by reference
• 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.
Object Oriented Programming
#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
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Return by reference
• 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
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Inline function
• 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 functionname(parameters)
{
// function code
}
Object Oriented Programming
#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
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Inline function
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Function with default arguments
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
#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
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)
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
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.
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;
}
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);
// 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
// The third 'func' is called
obj1.func(85,64);
return 0;
}
Department of E&TC Engineering, MCERC, Nashik
this pointer
• 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 to1. 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
•
#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;
}
};
Output:
object of address:0x7ffd84be86d0
a=10
b=20
int main()
{
Test t;
t.show();
return 0;
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Dynamic initialization of variables
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Memory management operators
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Memory management operators
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
new operator
•
• 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.,
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
delete operator
•
• 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;
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Operators in C++
•
• 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
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Member dereferencing Operators
•
• 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
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Scope resolution operators
•
•
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;
}
Object Oriented Programming
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.
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Scope resolution operators
Blocks in c++ are often nested•
e.g.,
{
int x=10;
{
block 1
block 2
int x=1;
}
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Scope resolution operators
•
•
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:
•
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.
: : variable–name;
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Scope resolution operators
•
#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.
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Typecast operator
•
• It is a mechanism which enables a variable of one datatype to be converted to another
datatype.
• Type of typecasting:
1. Implicit
2. Explicit
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Implicit typecasting
•
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Implicit typecasting
•
#include<iostream>
using namespace std;
Int main()
{
short a=100;
int b;
//initializing variable of short datatype
//declaring variable of integer datatype
b=a;
// implict type-casting
cout<<“a=”<<a;
cout<<“b=”<<b;
return 0;
}
Output:
a=100
b=100
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Explicit typecasting
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Explicit typecasting
•
• 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);
#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;
}
Object Oriented Programming
Output:
var1=25
var2= 35.87
float to integer = 25
integer to float = 35
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Operator precedence
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Operator Precedence
•
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Operator Precedence
•
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Operator Precedence
•
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Operator Precedence
•
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
• 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;
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
•
• 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
Compile time
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.
Runtime
• You will see the output "Hello World" printed on the screen.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Array
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Array
• 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].
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Array
• 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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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;
}
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Array Elements Store in Memory:
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
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.
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Thank You….