0% found this document useful (0 votes)
144 views95 pages

CS 214 Object Oriented Programming: Department of Computer Science and Engineering

CS 214 is an object oriented programming course offered by the computer science department. The course aims to teach object oriented programming concepts like abstraction, encapsulation, inheritance and polymorphism. The course outcomes are that students will be able to analyze OOP fundamentals, develop applications using OOP concepts, and implement OOP features to solve real-world problems. The document then discusses various OOP concepts like classes, objects, abstraction, encapsulation and polymorphism in detail with examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views95 pages

CS 214 Object Oriented Programming: Department of Computer Science and Engineering

CS 214 is an object oriented programming course offered by the computer science department. The course aims to teach object oriented programming concepts like abstraction, encapsulation, inheritance and polymorphism. The course outcomes are that students will be able to analyze OOP fundamentals, develop applications using OOP concepts, and implement OOP features to solve real-world problems. The document then discusses various OOP concepts like classes, objects, abstraction, encapsulation and polymorphism in detail with examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 95

CS 214 Object Oriented Programming

Department of Computer Science and


Engineering
CS 214 Object Oriented Programming
Teaching Scheme Credits: 02 + 01

Theory: 3 Hrs / Week Practical: 2Hrs/Week

• Course Objectives:
1) To understand the concepts of Object Oriented Programming.
2) To design and implement applications using various OOP features
3) To build foundation for advanced programming

• Course Outcomes:
1) Analyze the fundamentals of Object Oriented Programming.
2) Ability to develop applications using Object Oriented Programming Concepts.
3) Ability to implement features of object oriented programming to solve real world problems.

11/30/2021 OBJECT ORIENTED PROGRAMMING LABORATORY 2


Fundamentals of OOP

11/30/2021 Object Oriented Programming 3


Software Evolution

1,0

Machine Language
Assembly Language
Procedure - Oriented
Object Oriented Programming

11/30/2021 Object Oriented Programming 4


Procedural Programming
• Emphasis is on doing things (algorithms).
Main Program
• Large programs are divided into smaller programs known as
functions.
• Most ofFunction-1
the functions shareFunction-2
global data. Function-3

• Data move openly around the system from function to


function. Function-4 Function-5

• Functions transform data from one form to another.


• Employs top-down approach
Function-6 in program designFunction-8
Function-7

11/30/2021 Object Oriented Programming 5


Object Oriented Programming
• Design methodologyObject
for creating a non-rigid application
A Object B
• Works on entity called as objects
• Decompose problem in to Data Data
small unit of work which are accessed via Objects.
• Emphasis is on data rather than procedure.
• Data is hidden and cannotFunction
be accessed by external function. Function
• Objects may communicate with each other through function.
• Follows bottom up approach in program design.

Object C

Data

Function

11/30/2021 Object Oriented Programming 6


Features of OOP
• Programming language with OOP support has to fulfill these
features
– Abstraction
– Encapsulation
– Inheritance
– Polymorphism

11/30/2021 Object Oriented Programming 7


Real life Example
• Mobile as an object was designed to provide basic functionality as
– Calling and Receiving calls
– Messaging
• Thousands of new features and models are getting added

Mobile

iPhone Samsung Nokia

11/30/2021 Object Oriented Programming 8


Objects
• Any real world entity which can have some characteristics or which can
perform some work is called as Object.
– This object is also called as an instance i.e. - a copy of an entity in
programming language.
• A mobile manufacturing company, at a time manufactures lacs of pieces
of each model which are actually an instance.
• These objects are differentiated from each other via some identity (e.g.
IMEI number) or its characteristics.
Mobile mbl1 = new Mobile ();  
Mobile mbl2 = new Mobile ();  
11/30/2021 Object Oriented Programming 9
Class
class Mobile  
{  
     private:
 string IMEICode, SIMCard, Processor;  
• A Class Mobile
Class
is a plan which describes the
      object.
int InternalMemory;
      bool IsSingleSIM;
– WeProperties
call it as a blue print of how the object public: should be represented. 
     void GetIMEICode()  {  
• Mainly a class would consist of a name,
Processor attributes
         cout &
<< "IMEI Code - IEDF34343435235";  
IMEICode
operations. 
IsSingleSIM
     } 
     void Dial() {  
• A Mobile Methodscan be a class which has some          coutattributes like Profile
<< "Dial a number";  
     }  
Type,DialIMEI
Receive
Number, Processor, and some more.)
     void Receive() {   & operations
like Dial, Receive & SendMessage.          cout
SendMessage
     }  
<< "Receive a call";  
GetWifiConnection
ConnectBlueTooth      virtual void SendMessage(){  
GetIMEICode          cout << "Message Sent";  
     }  
11/30/2021  }  
Object Oriented Programming 10
Abstraction
• Abstraction - only show relevant details and rest all hide it
– its most important pillar in OOPS as it is providing us the technique to
hide irrelevant details from User
• Dialing a number calls some method internally which concatenate the
numbers and displays it on screen but what is it doing we don’t know.
• Clicking on green button actual send signals to calling person’s mobile
but we are unaware of how it is doing.
void Dial()  
{  
    //Write the logic  
    cout << "Dial a number";  
11/30/2021 Object Oriented Programming 11
}  
Encapsulation
• Encapsulation is defined as the process of enclosing one or more details
from outside world through access right.
– It says how much access should be given to particular details.
• Both Abstraction & Encapsulation works hand in hand because
Abstraction says what details to be made visible & Encapsulation
provides the level of access right to that visible details. i.e. – It
implements the desired level of abstraction.

private:
 string IMEICode = "76567556757656"; 

11/30/2021 Object Oriented Programming 12


Polymorphism
 class Samsumg :public  Mobile  
• Polymorphism
{   can be defined as the ability of doing the same operation
    public:
but with different type of input.
void GetWIFIConnection()  {  
– More
         precisely we say it as ‘many forms of single entity’
cout<<"WIFI connected";  
•      }    or Compile time polymorphism
Static
       //This is one method which shows camera functionality  
• Compile time polymorphism the compiler knows which overloaded
     void CameraClick()  {  
        
method cout<<“Camera clicked";  
it is going to call.
     }   
       //overloaded method which shows camera functionality as well but with panaroma mode  
      void CameraClick(string CameraMode) {  
        cout<<"Camera clicked in " + CameraMode + " Mode";  
     }  
}  

11/30/2021 Object Oriented Programming 13


Polymorphism
• Dynamic polymorphism
class Nokia : public Mobile  or Runtime polymorphism
{  
• Method Overriding is used to implement dynamic
     public :
polymorphism void GetBlueToothConnection()   {  
          cout<<"Bluetooth connected";  
• By runtime
      }  
polymorphism, we can point to any derived class
from     the//This is runtime polymorphism  
object of the base class at runtime that shows the
ability
       ofvoid SendMessage()  {  
runtime binding.
      cout<<"Message Sent to a group";  
    }  
}  

11/30/2021 Object Oriented Programming 14


Inheritance
• Ability to extend the functionality from base entity to new entity
belonging to same group.
– This will help us to reuse the functionality which is defined before. 
• There are mainly 4 types of inheritance:
– Single level inheritance
– Multi-level inheritance Mobile
– Hierarchical inheritance
iPhone Samsung Nokia
– Hybrid inheritance
– Multiple inheritance iPhone 5
Samsung
S4
Nokia
Lumia 625

Samsung
iPhone 6
S5

11/30/2021 Object Oriented Programming iPhone X 15


Inheritance
• Single level inheritance • Multi level inheritance
–  Single base class & a single derived – In Multilevel inheritance, there is more
class i.e. - A base mobile features are than one single level of derivation.
extended by Samsung brand. – E.g. After base features are extended by
Samsung brand, a new model is launched
Mobile with latest Android OS
Mobile

Samsung
Samsung

Samsung
11/30/2021 Object Oriented Programming S5 16
Inheritance
• Hierarchical inheritance • Hybrid inheritance
– Multiple derived class would be – Single, Multilevel, & hierarchal inheritance
extended from base class all together construct a hybrid inheritance.
– It’s similar to single level inheritance Mobile
but this time along with Samsung,
Nokia is also taking part in Samsung Nokia
inheritance.
Mobile Samsung
S5
Nokia
Lumia 625

Samsung Nokia

11/30/2021 Object Oriented Programming 17


Object based Vs Oriented Language
• objects-based programming are • Object-oriented programming language
languages that support programming incorporates two additional features,
with objects namely, inheritance and dynamic binding
• Feature that are required for object • Feature that are required for object based
based programming are: programming are:
– Data encapsulation – Data encapsulation
– Data hiding and access mechanisms – Data hiding and access mechanisms
– Automatic initialization and clear-up of – Automatic initialization and clear-up of objects
objects – Operator overloading
– Operator overloading – Inheritance
• E.g. Visual Basic – dynamic binding

11/30/2021 Object Oriented Programming 18


Application of OOP
• Real-business system are often complex and contain many objects with
complicated attributes and methods.
• Some of the areas of application of OOPs are:
– Real-time system
– Simulation and modeling
– Object-oriented data bases
– Hypertext, Hypermedia, and expertext
– AI and expert systems
– Neural networks and parallel programming
– Decision support and office automation systems
– CIM/CAM/CAD systems

11/30/2021 Object Oriented Programming 19


Why C++ ?
• C++ is a versatile language for handling very large programs including
editors, compilers, databases, communication systems and any complex
real life applications systems
– C++ allows create hierarchy related objects to build special object-oriented
libraries which can be used later by many programmers.
– the C part of C++ gives the language the ability to get closed to the machine-level
details.
– C++ programs are easily maintainable and expandable - it is very easy to add to
the existing structure of an object.
– It is expected that C++ will replace C as a general-purpose language in the near
future.
11/30/2021 Object Oriented Programming 20
BASICS OF C++

11/30/2021 Object Oriented Programming 21


Simple C++ Program
// Simple C++ program to display "Hello World"
// Header file for input output functions
instructs the compiler to include the contents of the file enclosed
#include<iostream>
within angular brackets into the source file.
 
using namespace std; defines a scope for the identifiers that are used in a program
 
// main function - where the execution of program begins
int main()
{
    // prints hello world
    cout<<"Hello World";
     
every main() returns an integer value to operating system
    return 0;
and therefore it should end with return (0) statement
}

11/30/2021 Object Oriented Programming 22


Structure of C++ Program
Include File
• Typical C++ program contains four sections
• It is a common practice to organize a program into Class Declaration
Server
three separate files Member Functions
• The class declarations are placed in a header file and Definitions
Member Function
Main Function Program
the definitions of member functions go into another Class Definition
file.
• The main program that uses the class is placed in a Main function program
third file which “includes” the previous two files as Client
well as any other file required

11/30/2021 Object Oriented Programming 23


C/C++ Compilation and Linking

Source code file


(program.c)

Preprocessor

Expanded source code


(program.i)
Compiler

Object Code
(program.obj)
Linker

Executable file
(program.exe)

11/30/2021 Object Oriented Programming 24


C/C++ Compilation and Linking

11/30/2021 Object Oriented Programming 25


FUNCTION in C++
• Function is a collection of declarations and statements
• A function must be defined prior to it’s use in the program

Type name_of_the_function (argument list)


{
//body of the function
}

11/30/2021 Object Oriented Programming 26


C++ Function Defination
• C++ function is defined in two steps (preferably but not
mandatory)
– Step #1 – declare the function signature in either a header file (.h file)
or before the main function of the program
– Step #2 – Implement the function in either an implementation file
(.cpp) or after the main function

27
The Syntactic Structure of a C++ Function

• A C++ function consists of two parts


– The function header, and
– The function body
• The function header has the following syntax

<return value> <name> (<parameter list>)

• The function body is simply a C++ code enclosed between { }


28
Example of User-defined
C++ Function

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

29
Example of User-defined
C++ Function
Function header

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

30
Example of User-defined
C++ Function
Function header Function body

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

31
Function Signature
• The function signature is actually similar to the function header
except in two aspects:
– The parameters’ names may not be specified in the function
signature
– The function signature must be ended by a semicolon
• Example Unnamed Semicolon
Parameter ;

double computeTaxes(double) ;

11/30/2021 Object Oriented Programming 32


Why Do We Need Function Signature?
• For Information Hiding
– If you want to create your own library and share it with your
customers without letting them know the implementation details,
you should declare all the function signatures in a header (.h) file and
distribute the binary code of the implementation file
• For Function Abstraction
– By only sharing the function signatures, we have the liberty to change
the implementation details from time to time to
• Improve function performance
• make the customers focus on the purpose of the function, not its
implementation

33
Example
#include <iostream> double computeTaxes(double income){
#include <string> if (income<5000) return 0.0;
using namespace std; return 0.07*(income-5000.0);
// Function Signature }
double getIncome(string); double getIncome(string prompt){
double computeTaxes(double); cout << prompt;
void printTaxes(double); double income;
void main() cin >> income;
{ return income;
// Get the income; }
double income = getIncome("Please enter the employee void printTaxes(double taxes){
income: "); cout << "The taxes is $" << taxes << endl;
// Compute Taxes }
double taxes = computeTaxes(income);
// Print employee taxes
printTaxes(taxes);
} 34
Default Arguments in Function
// C++ Program to demonstrate working of default
Case 1: No argument passed Case 2: First argument passed argument
• In C++ programming, you can provide default values for function
void temp (int = 10, float = 8.8); void temp (int = 10, float = 8.8); #include <iostream>
using namespace std;
parameters.
int main() {
temp();
int main() {
void display(char = '*', int = 1);
temp(6);
} • The idea behind default argument is simple. If a function is called
} int main()
{
void temp(int i, float f) { void temp(int i, float f) {
……… by passing argument/s, those arguments are used by the function.
……… cout << "No argument passed:\n";
display();
} }
• But if the argument/s are not passed while invoking a function cout << "\nFirst argument passed:\n";
display('#');
then, the default values are used.
Case 3: All arguments passed Case 4: Second argument passed cout << "\nBoth argument passed:\n";
void temp (int = 10, float = 8.8); void temp (int = 10, float = 8.8); display('$', 5);
• Default value/s are passed to argument/s in the function
int main() { int main() { return 0;
temp(6, -2.3); temp(3.4); }
}
prototype. } void display(char c, int n) {
void temp(int i, float f) { void temp(int i, float f) { for(int i = 1; i <= n; ++i) {
……… ……… cout << c;
} } }
11/30/2021 i = 3, f=8.8 Object Oriented Programming 35
Because, only the second argument cannot be passed. The
cout << endl;
Common Mistakes in DEFAULT ARGUMENTS

• void add(int a, int b = 3, int c, int d = 4);

• void add(int a=3, int b , int c, int d );

11/30/2021 Object Oriented Programming 36


Reference Variables
• A reference is an alias, or an alternate name to an existing
– Contains the address of a variable (like a pointer)

int x = 5;
int &z = x; // z is another name
for x
– No need to perform any dereferencing (unlike a pointer)
– Must be initialized when it is declared
int &y ; //Error: reference must be initialized

• References acts as function formal parameters to support pass-by-reference


• Any changes to reference variable inside the function are reflected outside the function

11/30/2021 Object Oriented Programming 37


How References Work?

type &newName = existingName;


int number = 88; // Declare an int variable called number
int & refNumber = number; // Declare a reference (alias)

11/30/2021 Object Oriented Programming 38


Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main() void main()
{ {
1 int x = 4; 4? x
int x = 4; // Local variable fun(x);
fun(x); cout << x << endl;
}
cout << x << endl; 39
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5; void fun( int & y)
} {
3 cout<<y<<endl;
void main() y=y+5;
{ }
int x = 4; // Local variable
fun(x); void main()
{
cout << x << endl; 4? x
int x = 4;
} 2
fun(x);
cout << x << endl;
} 40
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5; void fun( int & y )
} {
cout<<y<<endl;
void main() 4 y=y+5; 9
{ }
int x = 4; // Local variable
fun(x); void main()
{
cout << x << endl; 4? x
int x = 4;
} 2
fun(x);
cout << x << endl;
} 41
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5; void fun( int & y )
} {
cout<<y<<endl;
void main() y=y+5;
{ 5
}
int x = 4; // Local variable
fun(x); void main()
{
cout << x << endl; 9? x
int x = 4;
} 2
fun(x);
cout << x << endl;
} 42
Classes and Objects

11/30/2021 Object Oriented Programming 43


Class
• A way to bind data and associated function together
• An expanded concept of a data structure, instead of holding
only data, it can hold both data and function.
• The data is to be hidden from external use.

11/30/2021 Object Oriented Programming 44


Class

keyword
class class_name  
{   data member
private:
variable declaration;
body
public:
function declaration; member
…. function
} ; access
11/30/2021
specifiers
Object Oriented Programming 45
Access Specifiers
Less Restrictive
Class
Accessible from own class Private Area
public Accessible from derived class
No entry to Data
Accessible from class objects
Private area
Functions
Accessible from own class
protected
Accessible from derived class
Data
Entry allowed to
Public area
Functions
private Accessible from own class Public Area

More Restrictive
11/30/2021 *Object
By default all items defined in the class are private
Oriented Programming 46
Access Specifiers
Employee
Department Manager
public:
string name;
protected:
string designation;
private:
int Age;

CommissionEmployee

SalariedEmployee

11/30/2021 Object Oriented Programming 47


Access Specifiers

class Person {
public: //access control
string firstName; //these data members
string lastName; //can be accessed
tm dateOfBirth; //from anywhere
private:
string address; // can be accessed inside the class
long int insuranceNumber; //and by friend classes/functions
protected:
string phoneNumber; // can be accessed inside this class,
int salary; // by friend functions/classes and derived classes

};
11/30/2021 Object Oriented Programming 48
Objects
• A class provides the blueprints for objects, so basically an
object is created from a class.
• Objects of#include
a class are declared with exactly the same sort of
<iostream>
declaration
usingas variables
namespace std; of basic types
class Box {
public:
Class double length; // Length of a box
double breadth; // Breadth of a box Public data members
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box Objects of Box class
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
11/30/2021 } Object Oriented Programming 49
Objects
int main() {
Box Box1; // Declare Box1 of type Box
• The objects of class will have their Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
own copy of data members. // box 1 specification
• The public data members of Box1.height = 5.0;
Box1.length = 6.0;
Access data members
of Box1 object
objects of a class can be accessed Box1.breadth = 7.0;
// box 2 specification
using the direct member access Box2.height = 10.0; Access data members
operator (.) Box2.length = 12.0; of Box2 object
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;
11/30/2021
return 0;
Object Oriented Programming 50
}
"

Member Functions
class Box {
public:
double length, breadth, height;
• Can be defined inside class double getVolume(void) { // Returns box volume
return length * breadth * height; Inline function
return_type function_name (parameters) }
{ double getSurfaceArea(void); // returns surface area
// function body };
} // member function definition member function declaration
• Or outside the class double Box::getSurfaceArea(void) {
….
return_type class_name::function_name (formal} parameters) member function definition
{ int main() { outside class
// function body Box Box1;
} Box1.length = 10;
• Functions defined inside class are Box1.height = 20;
accessing member functions
Box1.breadth=30;
treated as inline functions by cout << “Volume of box: “ << Box1.getVolume() << endl;
compiler cout << “Surface Area of box: “ << Box1.getSurfaceArea() <<
endl;
11/30/2021 } Programming
Object Oriented 51
Array of Objects
#include <iostream> int main()
#include <string> {
using namespace std; Student st[5];
class Student for( int i=0; i<5; i++ )
{ {
string name; cout << "Student " << i + 1 << endl;
int marks;
cout << "Enter name" << endl;
public:
void getName() st[i].getName();
{ cout << "Enter marks" << endl;
getline( cin, name ); st[i].getMarks();
} }
void getMarks()
{
for( int i=0; i<5; i++ )
cin >> marks;
} {
void displayInfo() cout << "Student " << i + 1 << endl;
{ st[i].displayInfo();
cout << "Name : " << name << endl; }
cout << "Marks : " << marks << endl; return 0;
} }
};
 
11/30/2021 Object Oriented Programming 52
Dynamic memory allocation
• Dynamic memory allocation in C/C++ refers to performing
memory allocation manually by programmer.
• Dynamically allocated memory is allocated on Heap and non-
static and local variables get memory allocated on Stack
• Memory in C++ program is divided into two parts −
– The stack − All variables declared inside the function will take up
memory from the stack.
– The heap − This is unused memory of the program and can be used to
allocate the memory dynamically when program runs.
11/30/2021 Object Oriented Programming 53
Applications of Dynamic memory allocation

• To allocate memory of variable size which is not possible with


compiler allocated memory except variable length arrays.
• The most important use is flexibility provided to programmers.
We are free to allocate and deallocate memory whenever we
need and whenever we don’t need anymore. There are many
cases where this flexibility helps. Examples of such cases are
Linked List, Tree, etc

11/30/2021 Object Oriented Programming 54


new and delete Operators

• The new operator denotes a request for memory allocation on


the Heap
pointer-variable = new data-type;
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
// Combine declaration of pointer
// and their assignment
int *p = new int;

Initialize memory:
pointer-variable = new data-type(value);
Example:
int *p = new int(25);
11/30/2021 float *q = new float(75.25);
Object Oriented Programming 55
Pointers and Dynamic Memory

Here are the steps:

int * myIntPtr; // create an integer pointer variable


myIntPtr = new int; // create a dynamic variable of the size integer

new returns a pointer (or memory address) to the location where the
data is to be stored.
Pointers and Dynamic Memory

Free Store (heap)

int * myIntPtr
myIntPtr = new int;

myIntPtr
Pointers and Dynamic Memory

Free Store (heap) Use pointer variable

12 3
int * myIntPtr
myIntPtr = new int;
myIntPtr

*myIntPtr = 123;
Pointers and Dynamic Memory

• We can also allocate entire arrays with the new operator.


These are called dynamic arrays.

• This allows a program to ask for just the amount of


memory space it needs at run time.
Pointers and Dynamic Memory
Free Store (heap)

0 int * myIntPtr;
myIntPtr myIntPtr = new int[4];
1 3 2 5
2
3 myIntPtr[1] = 325;

Notice that the pointer symbol is


understood, no * is used to reference
the array element.
Pointers and Dynamic Memory

The new operator gets memory from the free store (heap).

When you are done using a memory location, it is your responsibility


to return the space to the free store. This is done with the delete
operator.

delete myIntPtr; // Deletes the memory pointed


delete [ ] arrayPtr; // to but not the pointer variable
Pointers and Dynamic Memory

Dynamic memory allocation provides a more flexible solution when


memory requirements vary greatly.

The memory pool for dynamic memory allocation is larger than that
set aside for static memory allocation.

Dynamic memory can be returned to the free store and allocated for
storing other data at later points in a program. (reused)
Example of Dynamic Arrays
#include <iostream>
using namespace std;
class Box {
public:
Box() {
cout << "Constructor called!" Output
<<endl; Constructor called!
} Constructor called!
~Box() { Constructor called!
cout << "Destructor called!" Constructor called!
<<endl; Destructor called!
} Destructor called!
}; Destructor called!
int main() { Destructor called!
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete
array
return 0;
11/30/2021
} Object Oriented Programming 63
}
Inline functions
• On function call instruction, CPU stores the memory address of
instruction following the function call
• CPU then transfers the control to callee function
• CPU executes callee function, stores function return value at
predefined memory location/register and returns control back
to caller
• It becomes an overhead if execution time of function is less
than switching time for caller function

11/30/2021 Object Oriented Programming 64


Inline functions
Mymaths.cpp

class ArithmaticOperations {
int AddNumbers(int x, int y){
main.cpp int z; PROLOG
z = x + y;
int main() { save regs
return z; EPILOG
int x = 20; pass args }
int y = 10;
inline int SubtractNumbers (int x, int y) {
cout << “Sum of Numbers: “ << AddNumbers(x, y) << endl; call AddNumbers int z;
cout << “Difference between Numbers: “ << SubtractNumbers(x, y) <<z endl;
= x – y; z = x – y;
cout << “Multiplication of numbers: “ << MultiplyNumbers(x, y) << endl;
restore regs return z;
}
}
int MultiplyNumbers (int x, int y) {
int z;
z = x * y;
return z;
}
}

11/30/2021 Object Oriented Programming 65


Inline Functions
• Inline functions reduce the call overhead.
• Inline functions gets expanded when called
– i.e. when inline function is called, entire code of inline function is
inserted/substituted at point of inline function call
– The substitution is performed by compiler at compile time
inline return-type function-name(parameters)
{
// function code
}

• By default compiler treats class methods defined under class as inline


functions
11/30/2021 Object Oriented Programming 66
class Employee {

Static Data Members


static int EmployeeId;
public:
int getEmpId (void) {
return ++EmployeeId;
• Data} members of the class which are shared by all objects are known as static
void addEmployee(str);
data
}; members.
void Employee::addEmployee(str name) { Employee
• Only one copy of static variable is maintained by the class and it is common
newId = getEmpId(); EmployeeId= 102
for all coutobjects.
<< “Added New Empl ” <<name <<“ with Id: “<<
newId <<endl;
• Static …. members are declared inside the class and defined outside the class.
• It}intisEmployee::EmployeeId Emp_A
initialized to zero when the first object of its class is created. Emp_B
EmployeeId=1 EmployeeId=2
• You cannot
int main() { initialize a static member variable inside the class declareation.
Employee Emp_A, Emp_B;
• It is Emp_A.addEmployee(“Amit”);
visible only within the class but its lifetime is the entire program.
• Static
}
Emp_B.addEmployee(“Bijoy”);
members are generally used to maintain values common to the entire
class.
# a.out
Added New Empl Amit with Id: 1
11/30/2021 Object Oriented Programming 67
Added New Empl Bijoy with Id: 2
Constructors
• A constructor is a special member function that is a member of a class and has same
name as that of class.
• It is used to initialize the object of the class type with a legal initial value.
• It is called constructor because it constructs the values of data members of the
class. Class
{
A
Default Values
Values
int a;
float b; a 0 0 10
char ch;
String str; b 0.0 0.0 20.0
boolean bl;

A() ch One Space m


{
a=10; str null null java
b=20.0;
ch=‘m’;
str=“java” bl false false true
bl=true
}
}

11/30/2021 Object Oriented Programming 68


Constructor - Declaration
• For the T class:
T(args); // inside class definition
or T::T(args); // outside class definition
class X {
int i ;
public:
int j,k ;
X() {
i = j = k =0; Inside class
}
};
X::X()
{
i = j = k =0; Outside class (a.k.a. inline definition)
}

11/30/2021 Object Oriented Programming 69


Constructor - Properties
• Automatically called when an object is created
Name same as Class name • We can define our own constructors
• They can not be inherited.
class X {
int i ; • These cannot be static.
public: Under public section
int j,k ; • Overloading of constructors is possible
X() {
i = j = k =0;
• Constructors can have default argument as other
} C++ functions.
};
• If you do not specify a constructor, the compiler
Does not return anything. Not generates a default constructor for you (expects
even void no parameters and has an empty body).
• Default and copy constructor are generated by the
compiler whenever required.

11/30/2021 Object Oriented Programming 70


Types of Constructors
• There are several forms in which a constructor can take its shape, namely

Constructors
Default
Parametrize
Default Parametrize Copy
d
Constructor d Constructor
Constructor
Constructor

11/30/2021 Object Oriented Programming 71


Default Constructor
• This constructor has no argument in it
• Compiler creates one, if not explicitly defined
• Default Constructor is also called as no argument constructor

class rectangle{ int main()


private: {
float height; rectangle rect;
float width; }
public:
rectangle(){ # a.out
cout <<“creating rectangle object”; creating rectangle object
}
};

11/30/2021 Object Oriented Programming 72


Parameterized Constructors
• A parameterized constructor is just one that has parameters specified in it.
• We can pass the arguments to constructor function when object is created.
• A constructor that can take arguments are called parameterized constructors

class rectangle{ int main()


private: {
float height; rectangle book(10.0, 20.0); //implicit call
float width; rectangle box = rectangle(20.0,30.0) //explicit call
public: rectangle eraser= rectangle(25.0, 35.0)
rectangle(float h, float w){ }
height=h;
width=w;
}
};
11/30/2021 Object Oriented Programming 73
Memory Allocation
• It is important to understand that compiler allocates memory to objects sequentially
and destroys in reverse order. This is because C++ compiler uses the concept of stack
in memory allocation and de-allocation
eraser

box
book

De-allocation
eraser
Allocation

box

book

11/30/2021 Object Oriented Programming 74


Default Parametrized Constructors
• Default argument is an argument to a function that a programmer is not required to specify.
• C++ allow the programmer to specify default arguments that always have a value, even if one is not
specified when calling the funtion
e.g. int power(int a, int b=2);
• The programmer may call this function in two ways
result = power(10,3); // result = 103 = 1000
result = power(10); // result = 102 = 100
• On similar lines, it is possible to define constructors with default parameters
rectangle(float h=1.0, float w=2.0)
and hence these are valid call statements
rectangle book(10.0, 20.0); // results into book object with height=10, width=20
rectangle box(10.0); // results into box object with height=10, width=1

11/30/2021 Object Oriented Programming 75


Constructor Overloading
• You can have more than one constructor in a class, as long as each has a different list
of arguments
class rectangle{
private:
float height;
float width;
public:
rectangle(){
height=width=10.0;
}
rectangle(float h, float w){
height=h;
width=w;
}
11/30/2021 }; Object Oriented Programming 76
Example of default and default
parameterized constructor
class rectangle{ void main()
private: {
float height; rectangle book(); //implicit call of default constructor
float width; rectangle box(20.0); //implicit call of default
public: parametrized constructor
rectangle eraser(10.0, 20.0); // explicit call of default
rectangle(float h, float w); parametrized constructor
rectangle(){ rectangle sharpener = rectangle(10);
height=width=1.0; rectangle geometry_box = rectangle(50.0,70.0);
} paper = rectangle (3.0, 6.0);
rectangle(float h, float w=5.0){ calculator = rectangle (15.0, 25.0) //explicit call
for existing object
height = h; }
width = w;
}
};
11/30/2021 Object Oriented Programming 77
Copy Constructor
• Copy
class constructor is used to declare and initialize an object
rectangle{ from
private:
another object
float height; int main()
• Ifpublic:
float width;
you have not defined a copy constructor, { the complier
rectangle book_1(10.0, 20.0);
automatically
rectangle(float h,creates
float w); it and it is public rectangle book_2(book_1);

• Copy constructor
rectangle(float h, float w){
}
always takes argument as a reference object.
height=h;
• The process
width=w; of initializing through a This would define the book_2 object and at
copy constructor
the same isvalue
time initialize it to the knownof
book_1. i.e. height and width of book_2
} as copy initialization.
object would be 10 and 20 respectively
rectangle(rectangle &p){
height = p.height;
width = p.width;
} T(const T &); or T::T(const T&);
};11/30/2021 Object Oriented Programming 78
Destructors
• A destructor is used to destroy the objects that have been created by a constructor.
• Like constructor, the destructor is a member function whose name is the same as
the class name but is preceded by a tilde.
~T();
• It is a good practice to declare destructors in a program since it releases memory
space for further use.
• Whenever new is used to allocate memory in the constructor, we should use delete
to free that memory.

11/30/2021 Object Oriented Programming 79


Destructors
int count=0; int main() #a.out
class rectangle { enter main
{ cout<<"\n enter main"; Created ObjectId:1
public:   rectangle a1,a2,a3,a4 Created ObjectId:2
rectangle(){ { Created ObjectId:3
count++; cout<<"\nEnter block1"; Created ObjectId:4
cout<<"\n Created ObjectId:"<<count; alpha a5; Enter block1
} } Created ObjectId:5
~rectangle() { { Destroyed ObjectId:5
count<<"\n Destroyed ObjectId:"<<count; cout<<"\nEnter block2"; Enter block2
count--; rectangle A6; Created ObjectId:5
} } Destroyed ObjectId:5
}; cout<<"\nRe-enter main"; Re-enter main
return 0; Destroyed ObjectId:4
} Destroyed ObjectId:3
Destroyed ObjectId:2
Destroyed ObjectId:1
11/30/2021 Object Oriented Programming 80
Destructors
• It is a special member function of a class, which is used to destroy the memory of
object
• Its name is same as class name but tilde sign preceding destructor
• It must be declared in public section
• It does not return any value; not even void
• It can be defined inline/offline
• Does not need to call because it gets call automatically whenever object is
destroyed from its scope
• It can be called explicitly also using delete operator
• It does not take parameters
• Destructor cannot be overloaded nor inherited.
11/30/2021 Object Oriented Programming 81
Friend Functions/Classes
• friends allow functions/classes access to private data of other classes.
• Friend functions
– A 'friend' function has access to all private and protected members (variables
and functions) of the class for which it is a 'friend'.
– friend function is not the actual member of the class.
– To declare a 'friend' function, include its prototype within the class, preceding it
with the C++ keyword 'friend'.

82
Example
class Employee
{
class Employee class Boss
private:
{ string name; {
private:
double salary; public:
stringvoid
friend name;
raiseSalary(double a, Employee &e); Boss();
Boss();
public:double salary; voidgiveRaise(double
void giveRaise(doubleamount);
amount);
Employee(); private:
Employee(string n, double s);
public: Employee e;
string getName();
Employee(); };
double getSalary(); Boss::Boss() {}
Employee(string n, double s);
};
string getName(); void Boss::giveRaise(double amount)
Employee::Employee() : name(""), salary(0) {}
double getSalary();
Employee::Employee(string n, double s): name(n), salary(s) {} {
}; Employee::getName() { return name; }
string raiseSalary(amount,e);
e.salary = e.salary + amount;
Employee::Employee()
double : name(""),
Employee::getSalary() salary(0)
{ return salary; } {} cout << e.getSalary() << endl;
e.salary << endl;
Employee::Employee(string
void raiseSalary(double a, Employeen, double
&e) s): name(n), salary(s) {} }
{string Employee::getName() { return name; }
e.salary
double+= a;// Normally not allowed
Employee::getSalary() to access
{ return e.salary
salary; }
} 11/30/2021 Object Oriented Programming 83
References

11/30/2021 Object Oriented Programming 84


BACKUP SLIDES

11/30/2021 Object Oriented Programming 85


Function Calls
class ArithmaticOperations {
int AddNumbers(int x, int y){
return x + y;
}
int SubtractNumbers (int x, int y) {
return x –y;
}
int MultiplyNumbers (int x, int y) {
return x * y;
}
}

int main() {
int x = 20;
int y = 10;
cout << “Sum of Numbers: “ << AddNumbers(x, y) << endl;
cout << “Difference between Numbers: “ << SubtractNumbers(x, y) << endl;
cout << “Multiplication of numbers: “ << MultiplyNumbers(x, y) << endl;
}

11/30/2021 Object Oriented Programming 86


Inline functions
• Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return
statement doesn’t exist in function body.
5) If a function contains switch or goto statement.

11/30/2021 Object Oriented Programming 87


Function Calls
class ArithmaticOperations {
int AddNumbers(int x, int y){
return x + y;
}
int SubtractNumbers (int x, int y) {
return x –y;
}
int MultiplyNumbers (int x, int y) {
return x * y;
}
}

int main() {
int x = 20;
int y = 10;
cout << “Sum of Numbers: “ << AddNumbers(x, y) << endl;
cout << “Difference between Numbers: “ << SubtractNumbers(x, y) << endl;
cout << “Multiplication of numbers: “ << MultiplyNumbers(x, y) << endl;
}

11/30/2021 Object Oriented Programming 88


• 1. Create a class named weather report that holds a daily weather report with
• data members day_of_month,hightemp,lowtemp,amount_rain and
• amount_snow. The constructor initializes the fields with default values: 99
• for day_of_month, 999 for hightemp,-999 for low emp and 0 for
• amount_rain and amount_snow. Include a function that prompts the user
• and sets values for each field so that you can override the default values.
• Write a program that creates a monthly report.
• Static member functions,friend class,this pointer,inline code and dynamic
• memory allocation :
• 2. Develop an object oriented program in C++ to create a database of the
• personnel information system containing the following information:
• Name,Date of Birth,Blood group,Height,Weight,Insurance Policy
• number,Contact address,telephone number,driving licence no. etc
• Construct the database with suitable member functions for initializing and
• destroying the data viz constructor,default constructor,copy
• constructor,destructor,static member functions,friend class,this
• pointer,inline code and dynamic memory allocation operators-new and
• delete.

11/30/2021 Object Oriented Programming 89


• A book shop maintains the inventory of books that are being sold at the shop. The list
• includes details such as author, title, price, publisher and stock position. Whenever a
• customer wants a book, the sales person inputs the title and author and the system
• searches the list and displays whether it is available or not. If it is not, an appropriate
• message is displayed. If it is, then the system displays the book details and requests
• for the number of copies required. If the requested copies book details and requests
• for the number of copies required. If the requested copies are available, the total cost
• of the requested copies is displayed; otherwise the message “Required copies not in
• stock” is displayed.
• Design a system using a class called books with suitable member functions and
• Constructors. Use new operator in constructors to allocate memory space required.
• Implement C++ program for the system.

11/30/2021 Object Oriented Programming 90


• Develop an object oriented program in C++ to create a
database of student information system containing the
following information: Name, Roll number, Class, division, Date
of Birth, Blood group, Contact address, telephone number,
driving license no. etc Construct the database with suitable
member functions for initializing and destroying the data viz
constructor, default constructor, Copy constructor, destructor,
static member functions, friend class, this pointer, inline code
and dynamic memory allocation operators-new and delete.
11/30/2021 Object Oriented Programming 91
• Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The
program should take two operands from user and performs the operation on those
two operands depending upon the operator entered by user. Use a switch statement
to select the operation. Finally, display the result.
• Some sample interaction with the program might look like this:
• Enter first number, operator, second number: 10 / 3
• Answer = 3.333333
• Do another (y/n)? y
• Enter first number, operator, second number: 12 + 100
• Answer = 112
• Do another (y/n)? n

11/30/2021 Object Oriented Programming 92


• Implement a class Quadratic that represents degree two polynomials i.e.,
polynomials of type ax2+bx+c. The class will require three data members
corresponding to a, b and c. Implement the following operations:
• 1. A constructor (including a default constructor which creates the 0 polynomial).
• 2. Overloaded operator+ to add two polynomials of degree 2.
• 3. Overloaded << and >> to print and read polynomials. To do this, you will need
to decide what you want your input and output format to look like.
• 4. A function eval that computes the value of a polynomial for a given value of x.
• 5. A function that computes the two solutions of the equation ax2+bx+c=0.

11/30/2021 Object Oriented Programming 93


• Implement a class CppArray which is identical to a one-dimensional
C++ array (i.e., the index set is a set of consecutive integers starting
at 0) except for the following :
• 1. It performs range checking.
• 2. It allows one to be assigned to another array through the use of
the assignment operator (e.g. cp1= cp2)
• 3. It supports a function that returns the size of the array.
• 4. It allows the reading or printing of array through the use of cout
and cin.
11/30/2021 Object Oriented Programming 94
11/30/2021 Object Oriented Programming 95

You might also like