0% found this document useful (0 votes)
319 views94 pages

Oop PPT 1

The document provides an overview of the contents and topics that will be covered in Unit 1 of an Object Oriented Programming course. It includes introductions to procedural, modular, object-oriented and generic programming techniques as well as the limitations of procedural programming and need for OOP. The key features of OOP such as objects, classes, data encapsulation, inheritance and polymorphism are also outlined. The document then continues discussing fundamentals of OOP in C++ including program structure, keywords, variables and functions. It provides examples comparing unstructured, procedural and OOP approaches.

Uploaded by

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

Oop PPT 1

The document provides an overview of the contents and topics that will be covered in Unit 1 of an Object Oriented Programming course. It includes introductions to procedural, modular, object-oriented and generic programming techniques as well as the limitations of procedural programming and need for OOP. The key features of OOP such as objects, classes, data encapsulation, inheritance and polymorphism are also outlined. The document then continues discussing fundamentals of OOP in C++ including program structure, keywords, variables and functions. It provides examples comparing unstructured, procedural and OOP approaches.

Uploaded by

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

Pro. R. G.

Masand, VIIT, Pune


R. G. Masand
OOP

1
CONTENTS OF UNIT - I
• Introduction to procedural, modular, object-oriented and generic
programming techniques

• Limitations of procedural programming

Pro. R. G. Masand, VIIT, Pune


• 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) 2
● Polymorphism(Function overloading and operator overloading)
FUNDAMENTALS OF OO PROGRAMMING
• C++ Program Structure
• C++ Identifiers

Pro. R. G. Masand, VIIT, Pune


• C++ Keywords
• Comments
• Primitive Built- in Types
• Variable declarations
• Local scope v/s Global Scope
• Literals
• Const keyword

3
FUNDAMENTALS OF OO PROGRAMMING(CONTINUED)
• Defining Function & Function Prototyping
• Function Declaration
• Function Calling
• Inline Function

Pro. R. G. Masand, VIIT, Pune


• 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 4

• I/O manipulation
A SURVEY OF PROGRAMMING TECHNIQUES

• Unstructured programming

Pro. R. G. Masand, VIIT, Pune


• Procedural programming

• Modular programming

• Object-oriented programming

• Generic programming

5
UNSTRUCTURED PROGRAMMING

• Only one Program i.e. main Program

• All the sequences of commands or statements in one


programs called main Program

Pro. R. G. Masand, VIIT, Pune


• E.g. Fortran, assembly language, old Basic

6
STRUCTURED PROGRAMMING
• Also called as Procedural Programming
• For each task procedure is created
The procedures are called from main

Pro. R. G. Masand, VIIT, Pune


7
MODULAR PROGRAMMING
• Procedures with some common functionality
are grouped together into separate modules
• Program is categorized into several smaller
modules

Pro. R. G. Masand, VIIT, Pune


• Each module can have its own data

8
OBJECT-ORIENTED PROGRAMMING

• Works on objects which is considered smallest


unit of the object oriented languages
• Focuses more on data rather than Procedures

Pro. R. G. Masand, VIIT, Pune


9
EXAMPLE
• Unstructured Programming:

#include

Pro. R. G. Masand, VIIT, Pune


#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
EXAMPLE
• Procedural Programming:

#include
#include

Pro. R. G. Masand, VIIT, Pune


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; 11
return z;
}
EXAMPLE
• Object Oriented programming

#include void main()


#include {
Addition obj; //object creation
class Addition cout << "Enter the numbers";

Pro. R. G. Masand, VIIT, Pune


{
int a,b,c;
obj.read();
public: obj.add();
void read() obj.display();
{ getch();
cin >> a; }
cin >> b;
}
void add()
{
c=a+b;
}
void display()
{
cout << "The sum is:" << c;
} 12
};
LIMITATIONS OF PROCEDURAL PROGRAMMING

• Poor real world model.

• No importance to data.

Pro. R. G. Masand, VIIT, Pune


• 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
Feature Procedure oriented Programming Object oriented Programming

In POP Program is divided into small parts In OOP, program is divided into parts
Divided Into
called functions called objects.

Importance In POP, Importance is not given to data In OOP, Importance is given to the data
but to functions as well as sequence of rather than procedures or functions
actions to be done. because it works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach

Pro. R. G. Masand, VIIT, Pune


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 In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
Expansion To add new data and function in POP is OOP provides an easy way to add new
not so easy. data and function
In POP, Most function uses Global data In OOP, data can not move easily from
for sharing that can be accessed freely function to function, it can be kept public
Data Access
from function to function in the system. or private so we can control the access of
data.
POP does not have any proper way for OOP provides Data Hiding so provides
Data Hiding
hiding data so it is less secure. more security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the
form of Function Overloading and15
Operator Overloading.
Examples Example of POP are : C, VB, Example of OOP are : C++, JAVA,
FORTRAN, Pascal. VB.NET, C#.NET.
GENERIC PROGRAMMING

• It is an idea that code should be as generic as


possible

Pro. R. G. Masand, VIIT, Pune


• Means writing templates

• e.g. container classes like arrays

16
Pro. R. G. Masand, VIIT, Pune
17
OBJECT ORIENTED FEATURES
INTRODUCTION

• C++ is a statically typed, compiled,


general-purpose, case-sensitive, free-form
programming language that supports procedural,

Pro. R. G. Masand, VIIT, Pune


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
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,

Pro. R. G. Masand, VIIT, Pune


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
CLASS AS ADT
• Abstract Data Types (ADTs)
● type implementation & operations
● hidden implementation
• built-in and user-defined types are ADTs

Pro. R. G. Masand, VIIT, Pune


client
ADT
Interface

Implementation client
use

20
manufacturer’s client
responsibility
C++ OBJECTS
• A class provides the blueprints for objects
• an object is created from a class
• Object is variable of class type

Pro. R. G. Masand, VIIT, Pune


• 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
ACCESSING THE DATA MEMBERS
• The public data members of objects of a class can be
accessed using the direct member access operator (.)
#include <iostream>  // box 2 specification
using namespace std; Box2.height = 10.0;
class Box{ Box2.length = 12.0;
public: Box2.breadth = 13.0; //

Pro. R. G. Masand, VIIT, Pune


double length; // Length of a box volume of //box 1
double breadth; // Breadth of a box volume = Box1.height *
double height; // Height of a box Box1.length * Box1.breadth;
}; cout << "Volume of Box1 : " <<
int main( ){ volume <<endl;  // volume of
Box Box1; // Declare Box1 of type Box box 2
Box Box2; // Declare Box2 of type volume = Box2.height *
Box double volume = 0.0; // Store the Box2.length * Box2.breadth;
volume of a box here cout << "Volume of Box2 : " <<
// box 1 specification Box1.height = 5.0; volume <<endl; return 0;}
Box1.length = 6.0;
Box1.breadth = 7.0;  22
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(.)

Pro. R. G. Masand, VIIT, Pune


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
MEMBERS OF CLASS(CONTINUED…)
• Member functions can be defined within the class
definition or separately using scope resolution
operator, ::

Pro. R. G. Masand, VIIT, Pune


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;
} 24
};// class end
MEMBERS OF CLASS(CONTINUED…)
• If you like you can define same function outside
the class using scope resolution operator, :: as
follows:

Pro. R. G. Masand, VIIT, Pune


double Box::getVolume(void){
return length * breadth * height;
}

25
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.

Pro. R. G. Masand, VIIT, Pune


• OOP encapsulates data (attributes) and functions
(behavior) into packages called objects

• E.g. class encapsulates data members and member


functions

26
DATA ABSTRACTION
• Abstraction refers to the act of representing
essential features without including the
background details or explanation

Pro. R. G. Masand, VIIT, Pune


• 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
27
control without having any knowledge of its internals.
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

Pro. R. G. Masand, VIIT, Pune


• 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
INFORMATION HIDING(CONTINUED)

• class Base {

Pro. R. G. Masand, VIIT, Pune


public: // public members go here

protected: // protected members go here

private: // private members go here

};

29
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

Pro. R. G. Masand, VIIT, Pune


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 30
child classes which are called derived classes
INHERITANCE

• Inheritance is the process by which objects of one


class acquired the properties of objects of another
classes.

Pro. R. G. Masand, VIIT, Pune


• In OOP, the concept of inheritance provides the
idea of reusability

• add additional features to an existing class without


modifying it

31
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

Pro. R. G. Masand, VIIT, Pune


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
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,

Pro. R. G. Masand, VIIT, Pune


● 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
33
information to be sent. Example:
Pro. R. G. Masand, VIIT, Pune
FUNDAMENTALS OF OO PROGRAMMING

34
USE OF C++

• C++ is used by hundreds of thousands of


programmers in essentially every application
domain.

Pro. R. G. Masand, VIIT, Pune


• 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 these35
systems are written in C++.
C++ PROGRAM STRUCTURE
#include <iostream>// headers
using namespace std; // use std namespace
// main() is where program execution begins.

Pro. R. G. Masand, VIIT, Pune


 int main()
{
cout << "Hello World"; // prints Hello World//
// statements
return 0;
}

36
C++ IDENTIFIER
• A C++ identifier is a name used to identify a
variable, function, class, module, or any other
user-defined item.

Pro. R. G. Masand, VIIT, Pune


• 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
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

Pro. R. G. Masand, VIIT, Pune


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
*/
39
• // prints Hello World ---single line comment
Pro. R. G. Masand, VIIT, Pune
40
Pro. R. G. Masand, VIIT, Pune
41
DATA TYPE PROGRAM
• #include <iostream>
• using namespace std; 
• int main(){
cout << "Size of char : " << sizeof(char) << endl;

Pro. R. G. Masand, VIIT, Pune


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;
} 42
// endl, which inserts a new-line character after every
line
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:

Pro. R. G. Masand, VIIT, Pune


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; 43
cout << f << endl ;
return 0;
VARIABLES

• In all programming languages, we need to use


various variables to store various information
• are nothing but reserved memory locations to store
values

Pro. R. G. Masand, VIIT, Pune


• 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,
44
digits, and the underscore character.
TYPES OF VARIABLE IN C++

Type Description

bool Stores either value true or false.

Pro. R. G. Masand, VIIT, Pune


Typically a single octet(one byte). This is an
char
integer type.

The most natural size of integer for the


int
machine.
float A single-precision floating point value.

double A double-precision floating point value.

void Represents the absence of type.


45

wchar_t A wide character type.


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>

Pro. R. G. Masand, VIIT, Pune


using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c; 46
return 0;
}
• 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

Pro. R. G. Masand, VIIT, Pune


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
GLOBAL VARIABLES : EXAMPLE
#include <iostream>
using namespace std;

// Global variable declaration:

Pro. R. G. Masand, VIIT, Pune


int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;

cout << g;

return 0; 48
}
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

Pro. R. G. Masand, VIIT, Pune


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
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.

Pro. R. G. Masand, VIIT, Pune


• 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
EXAMPLES

212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit

Pro. R. G. Masand, VIIT, Pune


032UU // Illegal: cannot repeat a suffix

85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
51
30ul // unsigned long
FLOATING POINT LITERALS
• A floating-point literal has an integer part, a
decimal point, a fractional part, and an exponent
part

3.14159 // Legal

Pro. R. G. Masand, VIIT, Pune


314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction

52
BOOLEAN LITERAL

• There are two Boolean literals and they are part of


standard C++ keywords:
● A value of true representing true.

Pro. R. G. Masand, VIIT, Pune


● A value of false representing false

53
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

Pro. R. G. Masand, VIIT, Pune


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
ESCAPE SEQUENCES
Escape sequence Meaning
\\ \ character
\' ' character
\" " character

Pro. R. G. Masand, VIIT, Pune


\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
Octal number of one to three
\ooo
digits
Hexadecimal number of one or 55
\xhh . . .
more digits
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

Pro. R. G. Masand, VIIT, Pune


• "hello, dear“

• "hello,
\
dear“

• "hello, " "d" "ear"

56
CONST KEYWORD
• use const prefix to declare constants with a specific type as
follows:
const type variable = value;

#include <iostream>

Pro. R. G. Masand, VIIT, Pune


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; 57
return 0;
}
DEFINING A FUNCTION
return_type function_name( parameter list )
{
body of the function
}

Pro. R. G. Masand, VIIT, Pune


• Return Type

• Function Name

• Parameters

• Function Body 58
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.

Pro. R. G. Masand, VIIT, Pune


• 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 59


calling the function.
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.

Pro. R. G. Masand, VIIT, Pune


• 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
FUNCTION CALLING

Call Type Description


This method copies the actual value of
an argument into the formal parameter
of the function. In this case, changes
Call by value
made to the parameter inside the

Pro. R. G. Masand, VIIT, Pune


function have no effect on the
argument.
This method copies the address of an
argument into the formal parameter.
Inside the function, the address is used
Call by pointer
to access the actual argument used in
the call. This means that changes made
to the parameter affect the argument.
This method copies the reference of an
argument into the formal parameter.
Inside the function, the reference is
Call by reference used to access the actual argument used
in the call. This means that changes 61
made to the parameter affect the
argument.
POINTER
• A pointer is a variable whose value is the address of
another variable
type *var-name;
type is the pointer's base type

Pro. R. G. Masand, VIIT, Pune


• 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
USING POINTERS IN C++
#include <iostream> 
using namespace std; 
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable

Pro. R. G. Masand, VIIT, Pune


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
OUTPUT

• Value of var variable: 20


• Address stored in ip variable: 0xbfc601ac

Pro. R. G. Masand, VIIT, Pune


• Value of *ip variable: 20

64
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

Pro. R. G. Masand, VIIT, Pune


int i = 17;
int& r = i;
Read the & in these declarations as reference

65
PROGRAM
#include <iostream>
using namespace std;
int main ()
{
// declare simple variables
int i;

Pro. R. G. Masand, VIIT, Pune


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

}
OUTPUT

Value of i : 5
Value of i reference : 5

Pro. R. G. Masand, VIIT, Pune


Value of d : 11.7
Value of d reference : 11.7

67
C++ REFERENCES V/S POINTERS
• References are often confused with pointers but
three major differences between references and
pointers are:

Pro. R. G. Masand, VIIT, Pune


● 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
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

Pro. R. G. Masand, VIIT, Pune



extraction operator, which is written as >> which are
two greater than signs

int main( )
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
69
cout << "Your name is: " << name << endl;
}
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:

Pro. R. G. Masand, VIIT, Pune


cin >> name >> age;

• This will be equivalent to the following two


statements:
cin >> name;
cin >> age;

70
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

Pro. R. G. Masand, VIIT, Pune


• 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++"; 71

cout << "Value of str is : " << str << endl;


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.

Pro. R. G. Masand, VIIT, Pune


• 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
• E.g.

Class test_ctor{
private :
int x,y;
public :
test_ctor(int x=0, int y=0){

Pro. R. G. Masand, VIIT, Pune


this→x = x;
this→ y=y;
}
tets_cot(){
//some code here….
}
void display(){
// some code goes here…..
}

73
}
CONTINUED….
void main(){
test_ctor t1(10,20);

Pro. R. G. Masand, VIIT, Pune


tets_ctor t2;
test_ctor t3;
t3.display();

74
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

Pro. R. G. Masand, VIIT, Pune


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
76
E.g.

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

Pro. R. G. Masand, VIIT, Pune


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
77
• The compiler can ignore the inline qualifier in case
defined function is more than a line.
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; 

Pro. R. G. Masand, VIIT, Pune


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
}
OUTPUT

Max (20,10): 20

Pro. R. G. Masand, VIIT, Pune


Max (0,200): 200

Max (100,1010): 1010

79
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

Pro. R. G. Masand, VIIT, Pune


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
80
present
#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;

Pro. R. G. Masand, VIIT, Pune


// 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. 81
cout << "Total objects: " << Box::objectCount << endl; 
return 0;
OUTPUT

Constructor called.
Constructor called.

Pro. R. G. Masand, VIIT, Pune


Total objects: 2

82
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

Pro. R. G. Masand, VIIT, Pune


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
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

Pro. R. G. Masand, VIIT, Pune


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 84
required memory can be determined at run time
DYNAMIC MEMORY ALLOCATION AND
DE-ALLOCATION(CNTD….)

• In static memory allocation, decision of


memory allocation is done at compile time
e.g. int a;

Pro. R. G. Masand, VIIT, Pune


● During run time variables are created

• In dynamic allocation both decision &


allocation of memory is done during
execution time.

85
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

Pro. R. G. Masand, VIIT, Pune


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
• E.g.
#include<iostream>
using namespace std;
int main()
{
int n, *pointer,c;
cout<<“enter an integer\n”;

Pro. R. G. Masand, VIIT, Pune


cin>>n;
pointer = new int[n];
cout<<“enter”<<n<<“ integers\n”;
for(c=0;c<n;c++)
cin>>pointer[c];
cout<<“elements entered by you are\n”;
for(c=0;c<n;c++)
cout<<poineter[c]<<endl;

delete[] pointer;
return 0;
87
}
NEW OPERATOR
void main(){
int x, float y, int *p;
p = new int;
}

Pro. R. G. Masand, VIIT, Pune


➢ 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
NAMED & NAMELESS OBJECTS....!!!
class shape{
private :

Pro. R. G. Masand, VIIT, Pune


int a,b;
};

shape p; → name object created (p)


Shape *q;
q = new shape; → name less object created.

89
• E.g. New and delete void main(){
operator
Class example { example *p1,*p2;
private : p1 = new example;
int i, float a; p2 = new
example(15,30.5);
public :

Pro. R. G. Masand, VIIT, Pune


delete p1;
example(){ delete p2;
i=0;
a=0.0; }
}
Example(int ii, float aa){
i = ii;
a= aa;
} 90

};
THIS POINTER
• Also called as constant pointer

• “this” keyword is used to identify between local and


instance variables

Pro. R. G. Masand, VIIT, Pune


91
• Class this_test{
private :
int i, float a;
public :
void setdata(int i, float a){

Pro. R. G. Masand, VIIT, Pune


this→i = i;
this→ a= a;
}
};
void main(){
this_test t1,t2;
t1.setdata(10,20.5);
}
92
FORMATTING FLAGS AND MANIPULATORS
• The following output manipulators control the
format of the output stream
• Include <iomanip>

Pro. R. G. Masand, VIIT, Pune


• 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
REFERENCES

• Let us c++ by yashwant kaetkar

Pro. R. G. Masand, VIIT, Pune


• Object oriented programming with c++ by
balagurusamy

• http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cp
p/index.html

• http://www.cplusplus.com/reference/library/manipula
tors/
94

• http://www.cplusplus.com/doc/tutorial/

You might also like