SlideShare a Scribd company logo
OBJECT ORIENTED
PROGRAMMING(OOP)
UNIT-1
1
Prof. V. S. Meshram
Navsahyadri Group of Institutes, Pune
Department of Computer Engineering
CO’S
1) To explore the principles of Object Oriented
Programming (OOP).
2) To understand object oriented concepts such as
data abstraction, encapsulation, inheritance,
dynamic binding, and polymorphism.
3) To use the object-oriented paradigm in program
design.
4) To lay a foundation for advanced programming.
5) Provide programming insight using OOP
constructs.
6) To understand the use of Standard Template
Library(STL)
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)
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
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
5
A SURVEY OF PROGRAMMING
TECHNIQUES
• Unstructured programming
• Procedural programming
• Modular programming
• Object-oriented programming
• Generic programming
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
7
STRUCTURED PROGRAMMING
• Also called as Procedural Programming
• For each task procedure is created
• The procedures are called from main
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
9
OBJECT-ORIENTED PROGRAMMING
• Works on objects which is considered smallest unit of
the object oriented languages
• Focuses more on data rather than Procedures
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();
} 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;
}
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();
}
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.
14
PROCEDURAL V/S OBJECT ORIENTED
PROGRAMMING
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.
16
GENERIC PROGRAMMING
• It is an idea that code should be as generic as possible
• Means writing templates
• e.g. container classes like arrays
17
OBJECT ORIENTED FEATURES
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 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
}; 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
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.
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;}
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
}; 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
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;
}
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
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.
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
29
INFORMATION HIDING(CONTINUED)
• class Base {
public: // public members go here
protected: // protected members go here
private: // private members go here
};
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 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
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()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:
34
FUNDAMENTALS OF OO PROGRAMMING
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++.
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;
}
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 38
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
40
41
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
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;
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.
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.
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;
}
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
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;
}
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
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
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
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
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
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'). 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
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"
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;
}
58
DEFINING A FUNCTION
return_type function_name( parameter list )
{
body of the function
}
• Return Type
• Function Name
• Parameters
• Function Body 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. 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
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.
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 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;
} 64
OUTPUT
• Value of var variable: 20
• Address stored in ip variable: 0xbfc601ac
• Value of *ip variable: 20
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
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;
}
67
OUTPUT
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
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. 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;
}
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;
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;
}
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
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…..
}
}
74
CONTINUED….
void main(){
test_ctor t1(10,20);
tets_ctor t2;
test_ctor t3;
t3.display();
}
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.
76
• E.g.
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.
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;
} 79
OUTPUT
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
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
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;
}
82
OUTPUT
Constructor called.
Constructor called.
Total objects: 2
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.
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
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.
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
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;
}
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.
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.
→
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;
}
91
THIS POINTER
• Also called as constant pointer
• “this” keyword is used to identify between local and
instance variables
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);
}
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.
94
REFERENCES
• Let us c++ by yashwant kanetkar
• Object oriented programming with c++ by balagurusamy
• http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/index.
html
• http://www.cplusplus.com/reference/library/manipulators/
• http://www.cplusplus.com/doc/tutorial/ 95

More Related Content

Similar to Unit - I Fundamentals of Object Oriented Programming .pptx (20)

PPTX
oop.pptx
KabitaParajuli3
 
PPTX
1 intro
abha48
 
PPTX
Ch 1 Introduction to Object Oriented Programming.pptx
MahiDivya
 
PPTX
1.1-Introduction to Object oriented.pptx
naushigrdcs
 
PPTX
IET307 OOP - object oriented programming concepts.pptx
BasithAb2
 
PPTX
Object Oriented Programming
AyushiDubey19
 
PPT
Unit 5.ppt
JITTAYASHWANTHREDDY
 
PPTX
c++session 1.pptx
PadmaN24
 
PDF
@vtucode.in-module-1-c++-2022-scheme.pdf
TheertheshTheertha1
 
PPTX
c++.pptxwjwjsijsnsksomammaoansnksooskskk
mitivete
 
PDF
Computer_Programming_Part_II_Segment_01.pdf
et243047
 
PPTX
Principles of OOPs.pptx
LakshyaChauhan21
 
PDF
Oop basic overview
Deborah Akuoko
 
PPTX
Object oriented programming. (1).pptx
baadshahyash
 
PPTX
CPP_,module2_1.pptx
AbhilashTom4
 
PPTX
Classes and objects
Shailendra Veeru
 
PPTX
Chapter1 introduction
Jeevan Acharya
 
PPTX
Object Oriented Programming using C++ - OOPS concepts using C++ programming l...
PreethaV16
 
oop.pptx
KabitaParajuli3
 
1 intro
abha48
 
Ch 1 Introduction to Object Oriented Programming.pptx
MahiDivya
 
1.1-Introduction to Object oriented.pptx
naushigrdcs
 
IET307 OOP - object oriented programming concepts.pptx
BasithAb2
 
Object Oriented Programming
AyushiDubey19
 
c++session 1.pptx
PadmaN24
 
@vtucode.in-module-1-c++-2022-scheme.pdf
TheertheshTheertha1
 
c++.pptxwjwjsijsnsksomammaoansnksooskskk
mitivete
 
Computer_Programming_Part_II_Segment_01.pdf
et243047
 
Principles of OOPs.pptx
LakshyaChauhan21
 
Oop basic overview
Deborah Akuoko
 
Object oriented programming. (1).pptx
baadshahyash
 
CPP_,module2_1.pptx
AbhilashTom4
 
Classes and objects
Shailendra Veeru
 
Chapter1 introduction
Jeevan Acharya
 
Object Oriented Programming using C++ - OOPS concepts using C++ programming l...
PreethaV16
 

Recently uploaded (20)

PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Ad

Unit - I Fundamentals of Object Oriented Programming .pptx

  • 1. OBJECT ORIENTED PROGRAMMING(OOP) UNIT-1 1 Prof. V. S. Meshram Navsahyadri Group of Institutes, Pune Department of Computer Engineering
  • 2. CO’S 1) To explore the principles of Object Oriented Programming (OOP). 2) To understand object oriented concepts such as data abstraction, encapsulation, inheritance, dynamic binding, and polymorphism. 3) To use the object-oriented paradigm in program design. 4) To lay a foundation for advanced programming. 5) Provide programming insight using OOP constructs. 6) To understand the use of Standard Template Library(STL) 2
  • 3. 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) 3
  • 4. 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 4
  • 5. 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 5
  • 6. A SURVEY OF PROGRAMMING TECHNIQUES • Unstructured programming • Procedural programming • Modular programming • Object-oriented programming • Generic programming 6
  • 7. 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 7
  • 8. STRUCTURED PROGRAMMING • Also called as Procedural Programming • For each task procedure is created • The procedures are called from main 8
  • 9. 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 9
  • 10. OBJECT-ORIENTED PROGRAMMING • Works on objects which is considered smallest unit of the object oriented languages • Focuses more on data rather than Procedures 10
  • 11. 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(); } 11
  • 12. 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; } 12
  • 13. 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(); } 13
  • 14. LIMITATIONS OF PROCEDURAL PROGRAMMING • Poor real world model. • No importance to data. • No privacy. • No true reuse. • Functions and data should be treated equally. 14
  • 15. PROCEDURAL V/S OBJECT ORIENTED PROGRAMMING 15
  • 16. 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. 16
  • 17. GENERIC PROGRAMMING • It is an idea that code should be as generic as possible • Means writing templates • e.g. container classes like arrays 17
  • 19. 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 19
  • 20. 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 }; 20
  • 21. 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 21
  • 22. 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. 22
  • 23. 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;} 23
  • 24. 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 }; 24
  • 25. 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 25
  • 26. 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; } 26
  • 27. 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 27
  • 28. 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. 28
  • 29. 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 29
  • 30. INFORMATION HIDING(CONTINUED) • class Base { public: // public members go here protected: // protected members go here private: // private members go here }; 30
  • 31. 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 31
  • 32. 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 32
  • 33. 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()33
  • 34. 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: 34
  • 35. FUNDAMENTALS OF OO PROGRAMMING 35
  • 36. 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++. 36
  • 37. 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; } 37
  • 38. 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 38
  • 39. 39
  • 40. 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 40
  • 41. 41
  • 42. 42
  • 43. 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 43
  • 44. 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; 44
  • 45. 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. 45
  • 46. 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. 46
  • 47. 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; } 47
  • 48. • 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 48
  • 49. 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; } 49
  • 50. 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 50
  • 51. 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 51
  • 52. 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 52
  • 53. 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 53
  • 54. 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 54
  • 55. 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'). 55
  • 56. 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 56
  • 57. 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" 57
  • 58. 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; } 58
  • 59. DEFINING A FUNCTION return_type function_name( parameter list ) { body of the function } • Return Type • Function Name • Parameters • Function Body 59
  • 60. 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. 60
  • 61. 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 61
  • 62. 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. 62
  • 63. 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 63
  • 64. 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; } 64
  • 65. OUTPUT • Value of var variable: 20 • Address stored in ip variable: 0xbfc601ac • Value of *ip variable: 20 65
  • 66. 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 66
  • 67. 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; } 67
  • 68. OUTPUT Value of i : 5 Value of i reference : 5 Value of d : 11.7 Value of d reference : 11.7 68
  • 69. 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. 69
  • 70. 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; } 70
  • 71. 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; 71
  • 72. 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; } 72
  • 73. 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 73
  • 74. • 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….. } } 74
  • 75. CONTINUED…. void main(){ test_ctor t1(10,20); tets_ctor t2; test_ctor t3; t3.display(); } 75
  • 76. 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. 76
  • 78. 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. 78
  • 79. 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; } 79
  • 80. OUTPUT Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010 80
  • 81. 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 81
  • 82. #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; } 82
  • 84. 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. 84
  • 85. 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 85
  • 86. 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. 86
  • 87. 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 87
  • 88. • 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; } 88
  • 89. 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. 89
  • 90. NAMED & NAMELESS OBJECTS....!!! class shape{ private : int a,b; }; shape p; name object created (p) → Shape *q; q = new shape; name less object created. → 90
  • 91. • 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; } 91
  • 92. THIS POINTER • Also called as constant pointer • “this” keyword is used to identify between local and instance variables 92
  • 93. • 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); } 93
  • 94. 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. 94
  • 95. REFERENCES • Let us c++ by yashwant kanetkar • Object oriented programming with c++ by balagurusamy • http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/index. html • http://www.cplusplus.com/reference/library/manipulators/ • http://www.cplusplus.com/doc/tutorial/ 95