SlideShare a Scribd company logo
1 of 94
OOP
R. G. Masand
1
Pro.
R.
G.
Masand,
VIIT,
Pune
CONTENTS OF UNIT - I
• Introduction to procedural, modular, object-oriented and generic
programming techniques
• Limitations of procedural programming
• Need of object-oriented programming
• Object Oriented Programming features
● Objects
● Classes & Class as ADT
● Data members
● Methods
● Message passing
● Data encapsulation
● Data abstraction
● Information hiding
● Inheritance(Code Reuse)
● Polymorphism(Function overloading and operator overloading)
2
Pro.
R.
G.
Masand,
VIIT,
Pune
FUNDAMENTALS OF OO
PROGRAMMING
• C++ Program Structure
• C++ Identifiers
• C++ Keywords
• Comments
• Primitive Built- in Types
• Variable declarations
• Local scope v/s Global Scope
• Literals
• Const keyword
3
Pro.
R.
G.
Masand,
VIIT,
Pune
FUNDAMENTALS OF OO
PROGRAMMING(CONTINUED)
• Defining Function & Function Prototyping
• Function Declaration
• Function Calling
• Inline Function
• Pointers
• This pointer
• C++ References
• Standard INPUT & OUTPUT Streams
• Class Constructor & Destructor
• Static Keyword
• Static data members
• Static member function
• Dynamic memory Allocation & De-allocation
• New & Delete operator
• I/O manipulation
4
Pro.
R.
G.
Masand,
VIIT,
Pune
A SURVEY OF PROGRAMMING
TECHNIQUES
• Unstructured programming
• Procedural programming
• Modular programming
• Object-oriented programming
• Generic programming
5
Pro.
R.
G.
Masand,
VIIT,
Pune
UNSTRUCTURED PROGRAMMING
• Only one Program i.e. main Program
• All the sequences of commands or statements in one
programs called main Program
• E.g. Fortran, assembly language, old Basic
6
Pro.
R.
G.
Masand,
VIIT,
Pune
STRUCTURED PROGRAMMING
• Also called as Procedural Programming
• For each task procedure is created
• The procedures are called from main
7
Pro.
R.
G.
Masand,
VIIT,
Pune
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
8
Pro.
R.
G.
Masand,
VIIT,
Pune
OBJECT-ORIENTED PROGRAMMING
• Works on objects which is considered smallest
unit of the object oriented languages
• Focuses more on data rather than Procedures
9
Pro.
R.
G.
Masand,
VIIT,
Pune
EXAMPLE
• Unstructured Programming:
#include
#include
void 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;
getch();
} 10
Pro.
R.
G.
Masand,
VIIT,
Pune
EXAMPLE
• Procedural Programming:
#include
#include
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;
}
11
Pro.
R.
G.
Masand,
VIIT,
Pune
EXAMPLE
• Object Oriented programming
#include
#include
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; //object creation
cout << "Enter the numbers";
obj.read();
obj.add();
obj.display();
getch();
}
12
Pro.
R.
G.
Masand,
VIIT,
Pune
LIMITATIONS OF PROCEDURAL PROGRAMMING
• Poor real world model.
• No importance to data.
• No privacy.
• No true reuse.
• Functions and data should be treated
equally.
13
Pro.
R.
G.
Masand,
VIIT,
Pune
PROCEDURAL V/S OBJECT ORIENTED
PROGRAMMING
14
Pro.
R.
G.
Masand,
VIIT,
Pune
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 Example of POP are : C, VB,
FORTRAN, Pascal.
Example of OOP are : C++, JAVA,
VB.NET, C#.NET.
15
Pro.
R.
G.
Masand,
VIIT,
Pune
GENERIC PROGRAMMING
• It is an idea that code should be as generic as
possible
• Means writing templates
• e.g. container classes like arrays
16
Pro.
R.
G.
Masand,
VIIT,
Pune
OBJECT ORIENTED FEATURES
17
Pro.
R.
G.
Masand,
VIIT,
Pune
INTRODUCTION
• C++ is a statically typed, compiled, general-
purpose, case-sensitive, free-form programming
language that supports procedural, object-
oriented, and generic programming.
• C++ is regarded as a middle-level language, as it
comprises a combination of both high-level and
low-level language features
• Developed by Bjarne Stroustrup starting in 1979
at Bell Labs in Murray Hill, New Jersey
18
Pro.
R.
G.
Masand,
VIIT,
Pune
C++ CLASS DEFINITION
• It is template, format or blueprint
• Also can be said as user defined data Type
• A class definition starts with the keyword class
followed by the class name; and the class body,
enclosed by a pair of curly braces.
• Class definition must be followed by a semicolon
• Class contains data members and member function
class Box{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
}; 19
Pro.
R.
G.
Masand,
VIIT,
Pune
CLASS AS ADT
• Abstract Data Types (ADTs)
● type implementation & operations
● hidden implementation
• built-in and user-defined types are ADTs
client
Implementation
Interface
manufacturer’s
responsibility
ADT
use
client
client
20
Pro.
R.
G.
Masand,
VIIT,
Pune
C++ OBJECTS
• A class provides the blueprints for objects
• an object is created from a class
• Object is variable of class type
• Objects are declared the same way the variables
are declared
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their
own
copy of data members.
21
Pro.
R.
G.
Masand,
VIIT,
Pune
ACCESSING THE DATA MEMBERS
• The public data members of objects of a class can be
accessed using the direct member access operator (.)
#include <iostream>
using namespace std;
class Box{
public:
double length; // Length of a
box double breadth; // Breadth of a
box double height; // Height of a
box
};int main( ){
Box Box1; // Declare Box1 of type
Box Box Box2; // Declare Box2 of
type Box double volume = 0.0; //
Store the volume of a box here
// box 1 specification Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0; //
volume of //box 1
volume = Box1.height *
Box1.length * Box1.breadth;
cout << "Volume of Box1 : " <<
volume <<endl; // volume of
box 2
volume = Box2.height *
Box2.length * Box2.breadth;
cout << "Volume of Box2 : " <<
volume <<endl; return 0;}
22
Pro.
R.
G.
Masand,
VIIT,
Pune
MEMBERS OF CLASS
• A member function of a class is a function that has
its definition or its prototype within the class
• Members are accessed using dot operator(.)
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box data
member double height; // Height of a
box
double getVolume(void); // Returns box
volume
// member function
};
23
Pro.
R.
G.
Masand,
VIIT,
Pune
MEMBERS OF CLASS(CONTINUED…)
• Member functions can be defined within the class
definition or separately using scope resolution
operator, ::
class Box{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void){
return length * breadth * height;
}
};// class end
24
Pro.
R.
G.
Masand,
VIIT,
Pune
MEMBERS OF CLASS(CONTINUED…)
• If you like you can define same function outside
the class using scope resolution operator, :: as
follows:
double Box::getVolume(void){
return length * breadth * height;
}
25
Pro.
R.
G.
Masand,
VIIT,
Pune
DATA ENCAPSULATION
• The wrapping up of data and function into a single
unit (called class) is known as encapsulation. Data
and encapsulation is the most striking feature of a
class.
• OOP encapsulates data (attributes) and functions
(behavior) into packages called objects
• E.g. class encapsulates data members and member
functions
26
Pro.
R.
G.
Masand,
VIIT,
Pune
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 size,
wait, and cost, and function operate on these
attributes.
• E.g TV
● a television separates its internal implementation from
its external interface and we can play with its interfaces
like the power button, channel changer, and volume
control without having any knowledge of its internals.
27
Pro.
R.
G.
Masand,
VIIT,
Pune
INFORMATION HIDING
• Data hiding is one of the important features of
Object Oriented Programming which allows
preventing the functions of a program to access
directly the internal representation of a class type
• The access restriction to the class members is
specified by the labeled public, private, and
protected sections within the class body
• private, and protected are called access
specifiers/modifiers.
• A class can have multiple public, protected, or
private labeled sections
• The default access for members and classes is
private 28
Pro.
R.
G.
Masand,
VIIT,
Pune
INFORMATION HIDING(CONTINUED)
• class Base {
public: // public members go here
protected: // protected members go here
private: // private members go here
};
29
Pro.
R.
G.
Masand,
VIIT,
Pune
INFORMATION HIDING(CONTINUED)
• A public member is accessible from anywhere
outside the class but within a program
• A private member variable or function cannot be
accessed, or even viewed from outside the class.
Only the class and friend functions can access
private members.
• By default all the members of a class would be
private
• A protected member variable or function is very
similar to a private member but it provided one
additional benefit that they can be accessed in
child classes which are called derived classes
30
Pro.
R.
G.
Masand,
VIIT,
Pune
INHERITANCE
• Inheritance is the process by which objects of one
class acquired the properties of objects of another
classes.
• In OOP, the concept of inheritance provides the
idea of reusability
• add additional features to an existing class without
modifying it
31
Pro.
R.
G.
Masand,
VIIT,
Pune
POLYMORPHISM
• Polymorphism is another important OOP concept.
Polymorphism, a Greek term, means the ability to
take more than on form
• An operation may exhibit different behavior is
different instances.
• The process of making an operator to exhibit
different behaviors in different instances is known
as operator overloading.
• Using a single function name to perform different
type of task is known as function overloading.
• E.g. abs(parameter type) instead of fabs(),labs(),abs()
32
Pro.
R.
G.
Masand,
VIIT,
Pune
MESSAGE PASSING
• An object-oriented program consists of a set of
objects that communicate with each other. The
process of programming in an object-oriented
language, involves the following basic steps:
● Creating classes that define object and their behaviour,
● Creating objects from class definitions, and
● Establishing communication 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:
33
Pro.
R.
G.
Masand,
VIIT,
Pune
FUNDAMENTALS OF OO
PROGRAMMING
34
Pro.
R.
G.
Masand,
VIIT,
Pune
USE OF C++
• C++ is used by hundreds of thousands of
programmers in essentially every application
domain.
• C++ is being highly used to write device drivers
and other softwares that rely on direct
manipulation of hardware under real-time
constraints.
• C++ is widely used for teaching and research
because it is clean enough for successful teaching
of basic concepts.
• Anyone who has used either an Apple Macintosh
or a PC running Windows has indirectly used
C++ because the primary user interfaces of these
systems are written in C++.
35
Pro.
R.
G.
Masand,
VIIT,
Pune
C++ PROGRAM STRUCTURE
#include <iostream>// headers
using namespace std; // use std namespace
// main() is where program execution begins.
int main()
{
cout << "Hello World"; // prints Hello
World// //
statements
return 0;
}
36
Pro.
R.
G.
Masand,
VIIT,
Pune
C++ IDENTIFIER
• 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 37
Pro.
R.
G.
Masand,
VIIT,
Pune
38
Pro.
R.
G.
Masand,
VIIT,
Pune
COMMENTS
• 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
39
Pro.
R.
G.
Masand,
VIIT,
Pune
40
Pro.
R.
G.
Masand,
VIIT,
Pune
41
Pro.
R.
G.
Masand,
VIIT,
Pune
DATA TYPE PROGRAM
• #include <iostream>
• using namespace std;
• int main(){
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
// endl, which inserts a new-line character after
every line
42
Pro.
R.
G.
Masand,
VIIT,
Pune
VARIABLES DEFINITION IN C++
• A variable definition means to tell the compiler where and how much to create the
storage for the variable
type variable_list;
• Example
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main (){
// Variable definition:
int a, b, c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c << endl ;
f = 70.0/3.0;
cout << f << endl ;
return 0;
43
Pro.
R.
G.
Masand,
VIIT,
Pune
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.
44
Pro.
R.
G.
Masand,
VIIT,
Pune
TYPES OF VARIABLE IN C++
Type Description
bool Stores either value true or false.
char
Typically a single octet(one byte). This is an
integer type.
int
The most natural size of integer for the
machine.
float A single-precision floating point value.
double A double-precision floating point value.
void Represents the absence of type.
wchar_t A wide character type.
45
Pro.
R.
G.
Masand,
VIIT,
Pune
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
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
46
Pro.
R.
G.
Masand,
VIIT,
Pune
• 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
47
Pro.
R.
G.
Masand,
VIIT,
Pune
GLOBAL VARIABLES : EXAMPLE
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
48
Pro.
R.
G.
Masand,
VIIT,
Pune
LITERALS
• Constants refer to fixed values that the program
may not alter and they are called literals.
• Constants can be of any of the basic data types and
can be divided into Integer Numerals, Floating-
Point Numerals, Characters, Strings and Boolean
Values.
• constants are treated just like regular variables
except that their values cannot be modified after
their definition
49
Pro.
R.
G.
Masand,
VIIT,
Pune
INTEGER LITERAL
• An integer literal can be a decimal, octal, or
hexadecimal constant.
• A prefix specifies the base or radix: 0x or 0X for
hexadecimal, 0 for octal, and nothing for decimal.
• An integer literal can also have a suffix that is a
combination of U and L, for unsigned and long,
respectively.
• The suffix can be uppercase or lowercase and can
be in any order
50
Pro.
R.
G.
Masand,
VIIT,
Pune
EXAMPLES
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
51
Pro.
R.
G.
Masand,
VIIT,
Pune
FLOATING POINT LITERALS
• A floating-point literal has an integer part, a
decimal point, a fractional part, and an exponent
part
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or
exponent
.e55 // Illegal: missing integer or
fraction
52
Pro.
R.
G.
Masand,
VIIT,
Pune
BOOLEAN LITERAL
• There are two Boolean literals and they are part of
standard C++ keywords:
● A value of true representing true.
● A value of false representing false
53
Pro.
R.
G.
Masand,
VIIT,
Pune
CHARACTER LITERALS
• Character literals are enclosed in single quotes
• If the literal begins with L (uppercase only), it is a
wide character literal (e.g., L'x') and should be
stored in wchar_t type of variable
• it is a narrow character literal (e.g., 'x') and can be
stored in a simple variable of char type
• A character literal can be a plain character (e.g., 'x'),
an escape sequence (e.g., 't'), or a universal
character (e.g., 'u02C0').
54
Pro.
R.
G.
Masand,
VIIT,
Pune
ESCAPE SEQUENCES
Escape sequence Meaning
  character
' ' character
" " character
? ? character
a Alert or bell
b Backspace
f Form feed
n Newline
r Carriage return
t Horizontal tab
v Vertical tab
ooo
Octal number of one to three
digits
xhh . . .
Hexadecimal number of one or
more digits
55
Pro.
R.
G.
Masand,
VIIT,
Pune
STRING LITERALS
• String literals are enclosed in double quotes
• A string contains characters that are similar to
character literals: plain characters, escape
sequences, and universal characters
• "hello, dear“
• "hello,

dear“
• "hello, " "d" "ear"
56
Pro.
R.
G.
Masand,
VIIT,
Pune
CONST KEYWORD
• use const prefix to declare constants with a specific type as
follows:
const type variable = value;
#include <iostream>
using namespace std;
int main()
• {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = 'n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}
57
Pro.
R.
G.
Masand,
VIIT,
Pune
DEFINING A FUNCTION
return_type function_name( parameter list )
{
body of the function
}
• Return Type
• Function Name
• Parameters
• Function Body 58
Pro.
R.
G.
Masand,
VIIT,
Pune
FUNCTION DECLARATIONS
• A function declaration tells the compiler about a
function name and how to call the function. The
actual body of the function can be defined
separately.
• A function declaration has the following parts:
return_type function_name( parameter list );
int max(int num1, int num2);
• Function declaration is required when you define a
function in one source file and you call that
function in another file
• should declare the function at the top of the file
calling the function.
59
Pro.
R.
G.
Masand,
VIIT,
Pune
FUNCTION CALLING
• While creating a C++ function, we give a definition
of what the function has to do.
• To use a function, we will have to call or invoke
that function.
• When a program calls a function, program control
is transferred to the called function
• A called function performs defined task and when
its return statement is executed or when its
function-ending closing brace is reached, it returns
program control back to the main program
• Actual arguments and formal arguments
60
Pro.
R.
G.
Masand,
VIIT,
Pune
FUNCTION CALLING
Call Type Description
Call by value
This method copies the actual value of
an argument into the formal parameter
of the function. In this case, changes
made to the parameter inside the
function have no effect on the
argument.
Call by pointer
This method copies the address of an
argument into the formal parameter.
Inside the function, the address is used
to access the actual argument used in
the call. This means that changes made
to the parameter affect the argument.
Call by reference
This method copies the reference of an
argument into the formal parameter.
Inside the function, the reference is
used to access the actual argument used
in the call. This means that changes
made to the parameter affect the
argument.
61
Pro.
R.
G.
Masand,
VIIT,
Pune
POINTER
• A pointer is a variable whose value is the address of
another variable
type *var-name;
type is the pointer's base type
• it must be a valid C++ type and var-name is the
name of the pointer variable. The asterisk we used
to declare a pointer is the same asterisk that you
use for multiplication
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to character 62
Pro.
R.
G.
Masand,
VIIT,
Pune
USING POINTERS IN C++
#include <iostream>
using namespace std;
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
} 63
Pro.
R.
G.
Masand,
VIIT,
Pune
OUTPUT
• Value of var variable: 20
• Address stored in ip variable: 0xbfc601ac
• Value of *ip variable: 20
64
Pro.
R.
G.
Masand,
VIIT,
Pune
C++ REFERENCES
• Think of a variable name as a label attached to the
variable's location in memory
• then think of a reference as a second label attached
to that memory location
int i = 17;
int& r = i;
Read the & in these declarations as reference
65
Pro.
R.
G.
Masand,
VIIT,
Pune
PROGRAM
#include <iostream>
using namespace std;
int main ()
{
// declare simple variables
int i;
double d;
// declare reference variables
int &r = i;
double & s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
66
Pro.
R.
G.
Masand,
VIIT,
Pune
OUTPUT
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
67
Pro.
R.
G.
Masand,
VIIT,
Pune
C++ REFERENCES V/S POINTERS
• References are often confused with pointers but
three major differences between references and
pointers are:
● We cannot have NULL references. We must always be
able to assume that a reference is connected to a
legitimate piece of storage.
● Once a reference is initialized to an object, it cannot be
changed to refer to another object. Pointers can be
pointed to another object at any time.
● A reference must be initialized when it is created.
Pointers can be initialized at any time.
68
Pro.
R.
G.
Masand,
VIIT,
Pune
THE STANDARD INPUT STREAM (CIN)
• The predefined object cin is an instance of istream
class
• The cin object is said to be attached to the standard
input device, which usually is the keyboard.
• The cin is used in conjunction with the stream
extraction operator, which is written as >> which are
two greater than signs
int main( )
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}
69
Pro.
R.
G.
Masand,
VIIT,
Pune
THE STANDARD INPUT STREAM
(CIN)(CNTD….)
• The stream extraction operator >> may be used
more than once in a single statement. To request
more than one datum you can use the following:
cin >> name >> age;
• This will be equivalent to the following two
statements:
cin >> name;
cin >> age;
70
Pro.
R.
G.
Masand,
VIIT,
Pune
THE STANDARD OUTPUT STREAM (COUT)
• The predefined object cout is an instance of ostream
class
• The cout object is said to be "connected to" the
standard output device, which usually is the display
screen
• The cout is used in conjunction with the stream
insertion operator, which is written as << which are
two less than signs
#include <iostream>
using namespace std;
int main( )
{
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
71
Pro.
R.
G.
Masand,
VIIT,
Pune
THE CLASS CONSTRUCTOR
• A class constructor is a special member function of
a class that is executed whenever we create new
objects of that class.
• A constructor will have exact same name as the
class and it does not have any return type at all, not
even void. Constructors can be very useful for
setting initial values for certain member variables.
• 0-argument constructor
• Parameterized constructor
72
Pro.
R.
G.
Masand,
VIIT,
Pune
• E.g.
Class test_ctor{
private :
int x,y;
public :
test_ctor(int x=0, int y=0){
this→x = x;
this→ y=y;
}
tets_cot(){
//some code here….
}
void display(){
// some code goes here…..
}
} 73
Pro.
R.
G.
Masand,
VIIT,
Pune
CONTINUED….
void main(){
test_ctor t1(10,20);
tets_ctor t2;
test_ctor t3;
t3.display();
}
74
Pro.
R.
G.
Masand,
VIIT,
Pune
THE CLASS DESTRUCTOR
• A destructor is a special member function of a
class that is executed whenever an object of it's
class goes out of scope or whenever the delete
expression is applied to a pointer to the object of
that class.
• A destructor will have exact same name as the class
prefixed with a tilde (~) and it can neither return a
value nor can it take any parameters. Destructor
can be very useful for releasing resources before
coming out of the program like closing files,
releasing memories etc.
75
Pro.
R.
G.
Masand,
VIIT,
Pune
• E.g.
76
Pro.
R.
G.
Masand,
VIIT,
Pune
INLINE FUNCTION
• C++ inline function is powerful concept that is
commonly used with classes
• If a function is inline, the compiler places a copy of
the code of that function at each point where the
function is called at compile time.
• Any change to an inline function could require all
clients of the function to be recompiled because
compiler would need to replace all the code once
again otherwise it will continue with old
functionality.
• To inline a function, place the keyword inline
before the function name and define the function
before any calls are made to the function
• The compiler can ignore the inline qualifier in case
defined function is more than a line.
77
Pro.
R.
G.
Masand,
VIIT,
Pune
INLINE (CNTD…)
• A function definition in a class definition is an inline
function definition, even without the use of the inline
specifier
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the programint
main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
78
Pro.
R.
G.
Masand,
VIIT,
Pune
OUTPUT
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
79
Pro.
R.
G.
Masand,
VIIT,
Pune
STATIC KEYWORD
• We can define class members static using static
keyword
• When we declare a member of a class as static it
means no matter how many objects of the class
are created, there is only one copy of the static
member.
• A static member is shared by all objects of the
class
• All static data is initialized to zero when the first
object is created, if no other initialization is
present
80
Pro.
R.
G.
Masand,
VIIT,
Pune
#include <iostream>
using namespace std;
class Box{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void){
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects.
cout << "Total objects: " << Box::objectCount << endl;
return 0;
}
81
Pro.
R.
G.
Masand,
VIIT,
Pune
OUTPUT
Constructor called.
Constructor called.
Total objects: 2
82
Pro.
R.
G.
Masand,
VIIT,
Pune
STATIC FUNCTION MEMBERS
• By declaring a function member as static, we make
it independent of any particular object of the class
• A static member function can be called even if no
objects of the class exist and the static functions
are accessed using only the class name and the
scope resolution operator ::
• A static member function can only access static
data member, other static member functions and
any other functions from outside the class.
Program during labs.
83
Pro.
R.
G.
Masand,
VIIT,
Pune
DYNAMIC MEMORY ALLOCATION AND DE-
ALLOCATION
• Memory in your C++ program is divided into two
parts
● The stack: All variables declared inside the function will
take up memory from the stack → Static memory
allocation
● The heap: This is unused memory of the program and
can be used to allocate the memory dynamically when
program runs.
→ Dynamic memory allocation
• Many times, we are not aware in advance how
much memory we will need to store particular
information in a defined variable and the size of
required memory can be determined at run time
84
Pro.
R.
G.
Masand,
VIIT,
Pune
DYNAMIC MEMORY ALLOCATION AND DE-
ALLOCATION(CNTD….)
• In static memory allocation, decision of
memory allocation is done at compile time
e.g. int a;
● During run time variables are created
• In dynamic allocation both decision &
allocation of memory is done during
execution time.
85
Pro.
R.
G.
Masand,
VIIT,
Pune
NEW AND DELETE OPERATOR
• We can allocate memory at run time within the
heap for the variable of a given type using a special
operator in C++ which returns the address of the
space allocated. This operator is called new
operator.
• Use delete operator, which de-allocates memory
previously allocated by new operator.
• Syntax :
new data-type;
data-type could be any built-in data type
86
Pro.
R.
G.
Masand,
VIIT,
Pune
• E.g.
#include<iostream>
using namespace std;
int main()
{
int n, *pointer,c;
cout<<“enter an integern”;
cin>>n;
pointer = new int[n];
cout<<“enter”<<n<<“ integersn”;
for(c=0;c<n;c++)
cin>>pointer[c];
cout<<“elements entered by you aren”;
for(c=0;c<n;c++)
cout<<poineter[c]<<endl;
delete[] pointer;
return 0;
}
87
Pro.
R.
G.
Masand,
VIIT,
Pune
NEW OPERATOR
void main(){
int x, float y, int *p;
p = new int;
}
➢ Now compiler makes an entry in symbol table
➢ new allocates memory, calls constructor
➢ New creates nameless objects.
➢ what is allocated must be de-allocated so use
delete operator which calls destructor, de-allocates
memory.
88
Pro.
R.
G.
Masand,
VIIT,
Pune
NAMED & NAMELESS OBJECTS....!!!
class shape{
private :
int a,b;
};
shape p; → name object created (p)
Shape *q;
q = new shape; → name less object created.
89
Pro.
R.
G.
Masand,
VIIT,
Pune
• E.g. New and delete
operator
Class example {
private :
int i, float a;
public :
example(){
i=0;
a=0.0;
}
Example(int ii, float aa){
i = ii;
a= aa;
}
};
void main(){
example *p1,*p2;
p1 = new example;
p2 = new
example(15,30.5);
delete p1;
delete p2;
}
90
Pro.
R.
G.
Masand,
VIIT,
Pune
THIS POINTER
• Also called as constant pointer
• “this” keyword is used to identify between local
and instance variables
91
Pro.
R.
G.
Masand,
VIIT,
Pune
• Class this_test{
private :
int i, float a;
public :
void setdata(int i, float a){
this→i = i;
this→ a= a;
}
};
void main(){
this_test t1,t2;
t1.setdata(10,20.5);
}
92
Pro.
R.
G.
Masand,
VIIT,
Pune
FORMATTING FLAGS AND MANIPULATORS
• The following output manipulators control the
format of the output stream
• Include <iomanip>
• The Range column tells how long the manipulator
will take effect: now inserts something at that point,
next affects only the next data element, and all
affects all subsequent data elements for the output
stream.
93
Pro.
R.
G.
Masand,
VIIT,
Pune
REFERENCES
• Let us c++ by yashwant kaetkar
• Object oriented programming with c++ by
balagurusamy
• http://www.uow.edu.au/~lukes/TEXTBOOK/notes-
cpp/index.html
• http://www.cplusplus.com/reference/library/manipula
tors/
• http://www.cplusplus.com/doc/tutorial/
94
Pro.
R.
G.
Masand,
VIIT,
Pune

More Related Content

Similar to OOP PPT 1.pptx

Fundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.pptFundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.pptAamirShahzad527024
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop Kumar
 
Oop(object oriented programming)
Oop(object oriented programming)Oop(object oriented programming)
Oop(object oriented programming)geetika goyal
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4Ali Aminian
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...Make Mannan
 
12. MODULE 1.pptx
12. MODULE 1.pptx12. MODULE 1.pptx
12. MODULE 1.pptxNIKHILAG9
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++jehan1987
 
c++session 1.pptx
c++session 1.pptxc++session 1.pptx
c++session 1.pptxPadmaN24
 

Similar to OOP PPT 1.pptx (20)

Lecture1
Lecture1Lecture1
Lecture1
 
Fundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.pptFundamentals of Programming in C++.ppt
Fundamentals of Programming in C++.ppt
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Introduction to oop
Introduction to oop Introduction to oop
Introduction to oop
 
advance-dart.pptx
advance-dart.pptxadvance-dart.pptx
advance-dart.pptx
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
Oop concept
Oop conceptOop concept
Oop concept
 
Oop ppt
Oop pptOop ppt
Oop ppt
 
Lecture02
Lecture02Lecture02
Lecture02
 
Oop(object oriented programming)
Oop(object oriented programming)Oop(object oriented programming)
Oop(object oriented programming)
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
OOP in java
OOP in javaOOP in java
OOP in java
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
 
12. MODULE 1.pptx
12. MODULE 1.pptx12. MODULE 1.pptx
12. MODULE 1.pptx
 
Object oriented programming in C++
Object oriented programming in C++Object oriented programming in C++
Object oriented programming in C++
 
c++session 1.pptx
c++session 1.pptxc++session 1.pptx
c++session 1.pptx
 

More from lathass5

print mod 2.pdf
print mod 2.pdfprint mod 2.pdf
print mod 2.pdflathass5
 
application_layer (1).pdf
application_layer (1).pdfapplication_layer (1).pdf
application_layer (1).pdflathass5
 
EV List.pdf
EV List.pdfEV List.pdf
EV List.pdflathass5
 
datalinklayermukesh-150130061041-conversion-gate01.pptx
datalinklayermukesh-150130061041-conversion-gate01.pptxdatalinklayermukesh-150130061041-conversion-gate01.pptx
datalinklayermukesh-150130061041-conversion-gate01.pptxlathass5
 
Data and Signals.ppt
Data and Signals.pptData and Signals.ppt
Data and Signals.pptlathass5
 
MODULE 5.pptx
MODULE 5.pptxMODULE 5.pptx
MODULE 5.pptxlathass5
 

More from lathass5 (7)

print mod 2.pdf
print mod 2.pdfprint mod 2.pdf
print mod 2.pdf
 
application_layer (1).pdf
application_layer (1).pdfapplication_layer (1).pdf
application_layer (1).pdf
 
EV List.pdf
EV List.pdfEV List.pdf
EV List.pdf
 
datalinklayermukesh-150130061041-conversion-gate01.pptx
datalinklayermukesh-150130061041-conversion-gate01.pptxdatalinklayermukesh-150130061041-conversion-gate01.pptx
datalinklayermukesh-150130061041-conversion-gate01.pptx
 
Data and Signals.ppt
Data and Signals.pptData and Signals.ppt
Data and Signals.ppt
 
dtoa.ppt
dtoa.pptdtoa.ppt
dtoa.ppt
 
MODULE 5.pptx
MODULE 5.pptxMODULE 5.pptx
MODULE 5.pptx
 

Recently uploaded

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 

Recently uploaded (20)

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 

OOP PPT 1.pptx

  • 2. CONTENTS OF UNIT - I • Introduction to procedural, modular, object-oriented and generic programming techniques • Limitations of procedural programming • Need of object-oriented programming • Object Oriented Programming features ● Objects ● Classes & Class as ADT ● Data members ● Methods ● Message passing ● Data encapsulation ● Data abstraction ● Information hiding ● Inheritance(Code Reuse) ● Polymorphism(Function overloading and operator overloading) 2 Pro. R. G. Masand, VIIT, Pune
  • 3. FUNDAMENTALS OF OO PROGRAMMING • C++ Program Structure • C++ Identifiers • C++ Keywords • Comments • Primitive Built- in Types • Variable declarations • Local scope v/s Global Scope • Literals • Const keyword 3 Pro. R. G. Masand, VIIT, Pune
  • 4. FUNDAMENTALS OF OO PROGRAMMING(CONTINUED) • Defining Function & Function Prototyping • Function Declaration • Function Calling • Inline Function • Pointers • This pointer • C++ References • Standard INPUT & OUTPUT Streams • Class Constructor & Destructor • Static Keyword • Static data members • Static member function • Dynamic memory Allocation & De-allocation • New & Delete operator • I/O manipulation 4 Pro. R. G. Masand, VIIT, Pune
  • 5. A SURVEY OF PROGRAMMING TECHNIQUES • Unstructured programming • Procedural programming • Modular programming • Object-oriented programming • Generic programming 5 Pro. R. G. Masand, VIIT, Pune
  • 6. UNSTRUCTURED PROGRAMMING • Only one Program i.e. main Program • All the sequences of commands or statements in one programs called main Program • E.g. Fortran, assembly language, old Basic 6 Pro. R. G. Masand, VIIT, Pune
  • 7. STRUCTURED PROGRAMMING • Also called as Procedural Programming • For each task procedure is created • The procedures are called from main 7 Pro. R. G. Masand, VIIT, Pune
  • 8. 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 8 Pro. R. G. Masand, VIIT, Pune
  • 9. OBJECT-ORIENTED PROGRAMMING • Works on objects which is considered smallest unit of the object oriented languages • Focuses more on data rather than Procedures 9 Pro. R. G. Masand, VIIT, Pune
  • 10. EXAMPLE • Unstructured Programming: #include #include void 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; getch(); } 10 Pro. R. G. Masand, VIIT, Pune
  • 11. EXAMPLE • Procedural Programming: #include #include 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; } 11 Pro. R. G. Masand, VIIT, Pune
  • 12. EXAMPLE • Object Oriented programming #include #include 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; //object creation cout << "Enter the numbers"; obj.read(); obj.add(); obj.display(); getch(); } 12 Pro. R. G. Masand, VIIT, Pune
  • 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. 13 Pro. R. G. Masand, VIIT, Pune
  • 14. PROCEDURAL V/S OBJECT ORIENTED PROGRAMMING 14 Pro. R. G. Masand, VIIT, Pune
  • 15. 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 Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET, C#.NET. 15 Pro. R. G. Masand, VIIT, Pune
  • 16. GENERIC PROGRAMMING • It is an idea that code should be as generic as possible • Means writing templates • e.g. container classes like arrays 16 Pro. R. G. Masand, VIIT, Pune
  • 18. INTRODUCTION • C++ is a statically typed, compiled, general- purpose, case-sensitive, free-form programming language that supports procedural, object- oriented, and generic programming. • C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features • Developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey 18 Pro. R. G. Masand, VIIT, Pune
  • 19. C++ CLASS DEFINITION • It is template, format or blueprint • Also can be said as user defined data Type • A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. • Class definition must be followed by a semicolon • Class contains data members and member function class Box{ public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; 19 Pro. R. G. Masand, VIIT, Pune
  • 20. CLASS AS ADT • Abstract Data Types (ADTs) ● type implementation & operations ● hidden implementation • built-in and user-defined types are ADTs client Implementation Interface manufacturer’s responsibility ADT use client client 20 Pro. R. G. Masand, VIIT, Pune
  • 21. C++ OBJECTS • A class provides the blueprints for objects • an object is created from a class • Object is variable of class type • Objects are declared the same way the variables are declared Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Both of the objects Box1 and Box2 will have their own copy of data members. 21 Pro. R. G. Masand, VIIT, Pune
  • 22. ACCESSING THE DATA MEMBERS • The public data members of objects of a class can be accessed using the direct member access operator (.) #include <iostream> using namespace std; class Box{ public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };int main( ){ Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; // box 2 specification Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.0; // volume of //box 1 volume = Box1.height * Box1.length * Box1.breadth; cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.height * Box2.length * Box2.breadth; cout << "Volume of Box2 : " << volume <<endl; return 0;} 22 Pro. R. G. Masand, VIIT, Pune
  • 23. MEMBERS OF CLASS • A member function of a class is a function that has its definition or its prototype within the class • Members are accessed using dot operator(.) class Box { public: double length; // Length of a box double breadth; // Breadth of a box data member double height; // Height of a box double getVolume(void); // Returns box volume // member function }; 23 Pro. R. G. Masand, VIIT, Pune
  • 24. MEMBERS OF CLASS(CONTINUED…) • Member functions can be defined within the class definition or separately using scope resolution operator, :: class Box{ public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box double getVolume(void){ return length * breadth * height; } };// class end 24 Pro. R. G. Masand, VIIT, Pune
  • 25. MEMBERS OF CLASS(CONTINUED…) • If you like you can define same function outside the class using scope resolution operator, :: as follows: double Box::getVolume(void){ return length * breadth * height; } 25 Pro. R. G. Masand, VIIT, Pune
  • 26. DATA ENCAPSULATION • The wrapping up of data and function into a single unit (called class) is known as encapsulation. Data and encapsulation is the most striking feature of a class. • OOP encapsulates data (attributes) and functions (behavior) into packages called objects • E.g. class encapsulates data members and member functions 26 Pro. R. G. Masand, VIIT, Pune
  • 27. 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 size, wait, and cost, and function operate on these attributes. • E.g TV ● a television separates its internal implementation from its external interface and we can play with its interfaces like the power button, channel changer, and volume control without having any knowledge of its internals. 27 Pro. R. G. Masand, VIIT, Pune
  • 28. INFORMATION HIDING • Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type • The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body • private, and protected are called access specifiers/modifiers. • A class can have multiple public, protected, or private labeled sections • The default access for members and classes is private 28 Pro. R. G. Masand, VIIT, Pune
  • 29. INFORMATION HIDING(CONTINUED) • class Base { public: // public members go here protected: // protected members go here private: // private members go here }; 29 Pro. R. G. Masand, VIIT, Pune
  • 30. INFORMATION HIDING(CONTINUED) • A public member is accessible from anywhere outside the class but within a program • A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members. • By default all the members of a class would be private • A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes 30 Pro. R. G. Masand, VIIT, Pune
  • 31. INHERITANCE • Inheritance is the process by which objects of one class acquired the properties of objects of another classes. • In OOP, the concept of inheritance provides the idea of reusability • add additional features to an existing class without modifying it 31 Pro. R. G. Masand, VIIT, Pune
  • 32. POLYMORPHISM • Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more than on form • An operation may exhibit different behavior is different instances. • The process of making an operator to exhibit different behaviors in different instances is known as operator overloading. • Using a single function name to perform different type of task is known as function overloading. • E.g. abs(parameter type) instead of fabs(),labs(),abs() 32 Pro. R. G. Masand, VIIT, Pune
  • 33. MESSAGE PASSING • An object-oriented program consists of a set of objects that communicate with each other. The process of programming in an object-oriented language, involves the following basic steps: ● Creating classes that define object and their behaviour, ● Creating objects from class definitions, and ● Establishing communication 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: 33 Pro. R. G. Masand, VIIT, Pune
  • 35. USE OF C++ • C++ is used by hundreds of thousands of programmers in essentially every application domain. • C++ is being highly used to write device drivers and other softwares that rely on direct manipulation of hardware under real-time constraints. • C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts. • Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++. 35 Pro. R. G. Masand, VIIT, Pune
  • 36. C++ PROGRAM STRUCTURE #include <iostream>// headers using namespace std; // use std namespace // main() is where program execution begins. int main() { cout << "Hello World"; // prints Hello World// // statements return 0; } 36 Pro. R. G. Masand, VIIT, Pune
  • 37. C++ IDENTIFIER • 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 37 Pro. R. G. Masand, VIIT, Pune
  • 39. COMMENTS • 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 39 Pro. R. G. Masand, VIIT, Pune
  • 42. DATA TYPE PROGRAM • #include <iostream> • using namespace std; • int main(){ cout << "Size of char : " << sizeof(char) << endl; cout << "Size of int : " << sizeof(int) << endl; cout << "Size of short int : " << sizeof(short int) << endl; cout << "Size of long int : " << sizeof(long int) << endl; cout << "Size of float : " << sizeof(float) << endl; cout << "Size of double : " << sizeof(double) << endl; cout << "Size of wchar_t : " << sizeof(wchar_t) << endl; return 0; } // endl, which inserts a new-line character after every line 42 Pro. R. G. Masand, VIIT, Pune
  • 43. VARIABLES DEFINITION IN C++ • A variable definition means to tell the compiler where and how much to create the storage for the variable type variable_list; • Example #include <iostream> using namespace std; // Variable declaration: extern int a, b; extern int c; extern float f; int main (){ // Variable definition: int a, b, c; float f; // actual initialization a = 10; b = 20; c = a + b; cout << c << endl ; f = 70.0/3.0; cout << f << endl ; return 0; 43 Pro. R. G. Masand, VIIT, Pune
  • 44. 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. 44 Pro. R. G. Masand, VIIT, Pune
  • 45. TYPES OF VARIABLE IN C++ Type Description bool Stores either value true or false. char Typically a single octet(one byte). This is an integer type. int The most natural size of integer for the machine. float A single-precision floating point value. double A double-precision floating point value. void Represents the absence of type. wchar_t A wide character type. 45 Pro. R. G. Masand, VIIT, Pune
  • 46. 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 #include <iostream> using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; } 46 Pro. R. G. Masand, VIIT, Pune
  • 47. • 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 47 Pro. R. G. Masand, VIIT, Pune
  • 48. GLOBAL VARIABLES : EXAMPLE #include <iostream> using namespace std; // Global variable declaration: int g = 20; int main () { // Local variable declaration: int g = 10; cout << g; return 0; } 48 Pro. R. G. Masand, VIIT, Pune
  • 49. LITERALS • Constants refer to fixed values that the program may not alter and they are called literals. • Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating- Point Numerals, Characters, Strings and Boolean Values. • constants are treated just like regular variables except that their values cannot be modified after their definition 49 Pro. R. G. Masand, VIIT, Pune
  • 50. INTEGER LITERAL • An integer literal can be a decimal, octal, or hexadecimal constant. • A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. • An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. • The suffix can be uppercase or lowercase and can be in any order 50 Pro. R. G. Masand, VIIT, Pune
  • 51. EXAMPLES 212 // Legal 215u // Legal 0xFeeL // Legal 078 // Illegal: 8 is not an octal digit 032UU // Illegal: cannot repeat a suffix 85 // decimal 0213 // octal 0x4b // hexadecimal 30 // int 30u // unsigned int 30l // long 30ul // unsigned long 51 Pro. R. G. Masand, VIIT, Pune
  • 52. FLOATING POINT LITERALS • A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part 3.14159 // Legal 314159E-5L // Legal 510E // Illegal: incomplete exponent 210f // Illegal: no decimal or exponent .e55 // Illegal: missing integer or fraction 52 Pro. R. G. Masand, VIIT, Pune
  • 53. BOOLEAN LITERAL • There are two Boolean literals and they are part of standard C++ keywords: ● A value of true representing true. ● A value of false representing false 53 Pro. R. G. Masand, VIIT, Pune
  • 54. CHARACTER LITERALS • Character literals are enclosed in single quotes • If the literal begins with L (uppercase only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable • it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type • A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., 't'), or a universal character (e.g., 'u02C0'). 54 Pro. R. G. Masand, VIIT, Pune
  • 55. ESCAPE SEQUENCES Escape sequence Meaning character ' ' character " " character ? ? character a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab ooo Octal number of one to three digits xhh . . . Hexadecimal number of one or more digits 55 Pro. R. G. Masand, VIIT, Pune
  • 56. STRING LITERALS • String literals are enclosed in double quotes • A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters • "hello, dear“ • "hello, dear“ • "hello, " "d" "ear" 56 Pro. R. G. Masand, VIIT, Pune
  • 57. CONST KEYWORD • use const prefix to declare constants with a specific type as follows: const type variable = value; #include <iostream> using namespace std; int main() • { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = 'n'; int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; } 57 Pro. R. G. Masand, VIIT, Pune
  • 58. DEFINING A FUNCTION return_type function_name( parameter list ) { body of the function } • Return Type • Function Name • Parameters • Function Body 58 Pro. R. G. Masand, VIIT, Pune
  • 59. FUNCTION DECLARATIONS • A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. • A function declaration has the following parts: return_type function_name( parameter list ); int max(int num1, int num2); • Function declaration is required when you define a function in one source file and you call that function in another file • should declare the function at the top of the file calling the function. 59 Pro. R. G. Masand, VIIT, Pune
  • 60. FUNCTION CALLING • While creating a C++ function, we give a definition of what the function has to do. • To use a function, we will have to call or invoke that function. • When a program calls a function, program control is transferred to the called function • A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program • Actual arguments and formal arguments 60 Pro. R. G. Masand, VIIT, Pune
  • 61. FUNCTION CALLING Call Type Description Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by pointer This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Call by reference This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. 61 Pro. R. G. Masand, VIIT, Pune
  • 62. POINTER • A pointer is a variable whose value is the address of another variable type *var-name; type is the pointer's base type • it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk we used to declare a pointer is the same asterisk that you use for multiplication int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch; // pointer to character 62 Pro. R. G. Masand, VIIT, Pune
  • 63. USING POINTERS IN C++ #include <iostream> using namespace std; int main () { int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0; } 63 Pro. R. G. Masand, VIIT, Pune
  • 64. OUTPUT • Value of var variable: 20 • Address stored in ip variable: 0xbfc601ac • Value of *ip variable: 20 64 Pro. R. G. Masand, VIIT, Pune
  • 65. C++ REFERENCES • Think of a variable name as a label attached to the variable's location in memory • then think of a reference as a second label attached to that memory location int i = 17; int& r = i; Read the & in these declarations as reference 65 Pro. R. G. Masand, VIIT, Pune
  • 66. PROGRAM #include <iostream> using namespace std; int main () { // declare simple variables int i; double d; // declare reference variables int &r = i; double & s = d; i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl; d = 11.7; cout << "Value of d : " << d << endl; cout << "Value of d reference : " << s << endl; return 0; } 66 Pro. R. G. Masand, VIIT, Pune
  • 67. OUTPUT Value of i : 5 Value of i reference : 5 Value of d : 11.7 Value of d reference : 11.7 67 Pro. R. G. Masand, VIIT, Pune
  • 68. C++ REFERENCES V/S POINTERS • References are often confused with pointers but three major differences between references and pointers are: ● We cannot have NULL references. We must always be able to assume that a reference is connected to a legitimate piece of storage. ● Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. ● A reference must be initialized when it is created. Pointers can be initialized at any time. 68 Pro. R. G. Masand, VIIT, Pune
  • 69. THE STANDARD INPUT STREAM (CIN) • The predefined object cin is an instance of istream class • The cin object is said to be attached to the standard input device, which usually is the keyboard. • The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs int main( ) { char name[50]; cout << "Please enter your name: "; cin >> name; cout << "Your name is: " << name << endl; } 69 Pro. R. G. Masand, VIIT, Pune
  • 70. THE STANDARD INPUT STREAM (CIN)(CNTD….) • The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following: cin >> name >> age; • This will be equivalent to the following two statements: cin >> name; cin >> age; 70 Pro. R. G. Masand, VIIT, Pune
  • 71. THE STANDARD OUTPUT STREAM (COUT) • The predefined object cout is an instance of ostream class • The cout object is said to be "connected to" the standard output device, which usually is the display screen • The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs #include <iostream> using namespace std; int main( ) { char str[] = "Hello C++"; cout << "Value of str is : " << str << endl; 71 Pro. R. G. Masand, VIIT, Pune
  • 72. THE CLASS CONSTRUCTOR • A class constructor is a special member function of a class that is executed whenever we create new objects of that class. • A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables. • 0-argument constructor • Parameterized constructor 72 Pro. R. G. Masand, VIIT, Pune
  • 73. • E.g. Class test_ctor{ private : int x,y; public : test_ctor(int x=0, int y=0){ this→x = x; this→ y=y; } tets_cot(){ //some code here…. } void display(){ // some code goes here….. } } 73 Pro. R. G. Masand, VIIT, Pune
  • 74. CONTINUED…. void main(){ test_ctor t1(10,20); tets_ctor t2; test_ctor t3; t3.display(); } 74 Pro. R. G. Masand, VIIT, Pune
  • 75. THE CLASS DESTRUCTOR • A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. • A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. 75 Pro. R. G. Masand, VIIT, Pune
  • 77. INLINE FUNCTION • C++ inline function is powerful concept that is commonly used with classes • If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. • Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality. • To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function • The compiler can ignore the inline qualifier in case defined function is more than a line. 77 Pro. R. G. Masand, VIIT, Pune
  • 78. INLINE (CNTD…) • A function definition in a class definition is an inline function definition, even without the use of the inline specifier #include <iostream> using namespace std; inline int Max(int x, int y) { return (x > y)? x : y; } // Main function for the programint main( ) { cout << "Max (20,10): " << Max(20,10) << endl; cout << "Max (0,200): " << Max(0,200) << endl; cout << "Max (100,1010): " << Max(100,1010) << endl; return 0; } 78 Pro. R. G. Masand, VIIT, Pune
  • 79. OUTPUT Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010 79 Pro. R. G. Masand, VIIT, Pune
  • 80. STATIC KEYWORD • We can define class members static using static keyword • When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. • A static member is shared by all objects of the class • All static data is initialized to zero when the first object is created, if no other initialization is present 80 Pro. R. G. Masand, VIIT, Pune
  • 81. #include <iostream> using namespace std; class Box{ public: static int objectCount; // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void){ Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects. cout << "Total objects: " << Box::objectCount << endl; return 0; } 81 Pro. R. G. Masand, VIIT, Pune
  • 82. OUTPUT Constructor called. Constructor called. Total objects: 2 82 Pro. R. G. Masand, VIIT, Pune
  • 83. STATIC FUNCTION MEMBERS • By declaring a function member as static, we make it independent of any particular object of the class • A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator :: • A static member function can only access static data member, other static member functions and any other functions from outside the class. Program during labs. 83 Pro. R. G. Masand, VIIT, Pune
  • 84. DYNAMIC MEMORY ALLOCATION AND DE- ALLOCATION • Memory in your C++ program is divided into two parts ● The stack: All variables declared inside the function will take up memory from the stack → Static memory allocation ● The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs. → Dynamic memory allocation • Many times, we are not aware in advance how much memory we will need to store particular information in a defined variable and the size of required memory can be determined at run time 84 Pro. R. G. Masand, VIIT, Pune
  • 85. DYNAMIC MEMORY ALLOCATION AND DE- ALLOCATION(CNTD….) • In static memory allocation, decision of memory allocation is done at compile time e.g. int a; ● During run time variables are created • In dynamic allocation both decision & allocation of memory is done during execution time. 85 Pro. R. G. Masand, VIIT, Pune
  • 86. NEW AND DELETE OPERATOR • We can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator. • Use delete operator, which de-allocates memory previously allocated by new operator. • Syntax : new data-type; data-type could be any built-in data type 86 Pro. R. G. Masand, VIIT, Pune
  • 87. • E.g. #include<iostream> using namespace std; int main() { int n, *pointer,c; cout<<“enter an integern”; cin>>n; pointer = new int[n]; cout<<“enter”<<n<<“ integersn”; for(c=0;c<n;c++) cin>>pointer[c]; cout<<“elements entered by you aren”; for(c=0;c<n;c++) cout<<poineter[c]<<endl; delete[] pointer; return 0; } 87 Pro. R. G. Masand, VIIT, Pune
  • 88. NEW OPERATOR void main(){ int x, float y, int *p; p = new int; } ➢ Now compiler makes an entry in symbol table ➢ new allocates memory, calls constructor ➢ New creates nameless objects. ➢ what is allocated must be de-allocated so use delete operator which calls destructor, de-allocates memory. 88 Pro. R. G. Masand, VIIT, Pune
  • 89. NAMED & NAMELESS OBJECTS....!!! class shape{ private : int a,b; }; shape p; → name object created (p) Shape *q; q = new shape; → name less object created. 89 Pro. R. G. Masand, VIIT, Pune
  • 90. • E.g. New and delete operator Class example { private : int i, float a; public : example(){ i=0; a=0.0; } Example(int ii, float aa){ i = ii; a= aa; } }; void main(){ example *p1,*p2; p1 = new example; p2 = new example(15,30.5); delete p1; delete p2; } 90 Pro. R. G. Masand, VIIT, Pune
  • 91. THIS POINTER • Also called as constant pointer • “this” keyword is used to identify between local and instance variables 91 Pro. R. G. Masand, VIIT, Pune
  • 92. • Class this_test{ private : int i, float a; public : void setdata(int i, float a){ this→i = i; this→ a= a; } }; void main(){ this_test t1,t2; t1.setdata(10,20.5); } 92 Pro. R. G. Masand, VIIT, Pune
  • 93. FORMATTING FLAGS AND MANIPULATORS • The following output manipulators control the format of the output stream • Include <iomanip> • The Range column tells how long the manipulator will take effect: now inserts something at that point, next affects only the next data element, and all affects all subsequent data elements for the output stream. 93 Pro. R. G. Masand, VIIT, Pune
  • 94. REFERENCES • Let us c++ by yashwant kaetkar • Object oriented programming with c++ by balagurusamy • http://www.uow.edu.au/~lukes/TEXTBOOK/notes- cpp/index.html • http://www.cplusplus.com/reference/library/manipula tors/ • http://www.cplusplus.com/doc/tutorial/ 94 Pro. R. G. Masand, VIIT, Pune