CS 214 Object Oriented Programming: Department of Computer Science and Engineering
CS 214 Object Oriented Programming: Department of Computer Science and Engineering
• 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.
1,0
Machine Language
Assembly Language
Procedure - Oriented
Object Oriented Programming
Object C
Data
Function
Mobile
private:
string IMEICode = "76567556757656";
Samsung
iPhone 6
S5
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
Preprocessor
Object Code
(program.obj)
Linker
Executable file
(program.exe)
27
The Syntactic Structure of a C++ Function
29
Example of User-defined
C++ Function
Function header
30
Example of User-defined
C++ Function
Function header Function body
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) ;
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
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
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
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
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
new returns a pointer (or memory address) to the location where the
data is to be stored.
Pointers and Dynamic Memory
int * myIntPtr
myIntPtr = new int;
myIntPtr
Pointers and Dynamic Memory
12 3
int * myIntPtr
myIntPtr = new int;
myIntPtr
*myIntPtr = 123;
Pointers and Dynamic Memory
0 int * myIntPtr;
myIntPtr myIntPtr = new int[4];
1 3 2 5
2
3 myIntPtr[1] = 325;
The new operator gets memory from the free store (heap).
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
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;
}
}
Constructors
Default
Parametrize
Default Parametrize Copy
d
Constructor d Constructor
Constructor
Constructor
box
book
De-allocation
eraser
Allocation
box
book
• 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.
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
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;
}
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;
}