Object Oriented Programming in C++
Object Oriented Programming in C++
Object Oriented Programming in C++
By Robert Lafore
What Is OOP ? - Part 1
What IS Object Oriented Programming ?
A programming paradigm does not refer to a specific language but rather to a way to build a program
or a methodology to apply.
Some languages make it easy to write in some paradigms but not others.
Some Programming Languages allow the programmer to apply more than one Paradigm.
Example of Programming Paradigms
Example of Previous Programming Paradigm
Procedural Programming
Procedural programming (PP), also known as inline programming takes a top-down approach. It is about
writing a list of instructions to tell the computer what to do step by step. It relies on procedures or routines.
Procedural Programming Example : Program to Calculate Average of Array Items
Calc Sum ( )
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects"
College Environment
Loyalty
Cart Bager
Card
What Is OOP ? - Part 2
Objects in College Management Program
College Environment
Object
Data
Operations ( )
Object Is comprised Of ?
Product
Data
1- Product _name ,
2- Product _code
3- Price
4- Producer
5-Discount
Operations ( )
1- Modify Price ()
2- Set Discount ()
3- Get Product Name ()
4- Get Product Price ()
Object Is comprised Of ?
Student
Data
1- Student_name ,
2- University_Id
3- Birth_Date
4- Address
5-GPA
6- Study_Level
Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student Address ()
Object Is comprised Of ?
Car
Data
1- Factory,
2- Model
3- Fuel_Capacity
4- No_of_doors
5-Color
6- Shape
Operations ( )
1- Set Factory Name()
2- Change Color ()
3- Get Car Info ()
4- ………..
Classes & Objects
What is Class ? Why we need It ?
Student 1 Student 2 Student 3
Data: Data: Data:
1- Student_name , 1- Student_name , 1- Student_name ,
2- University_Id 2- University_Id 2- University_Id
3- Birth_Date 3- Birth_Date 5-GPA
4- Address 4- Address 6- Study_Level
5-GPA 6- Study_Level
6- Study_Level
Operations ( )
Operations ( )
Operations ( ) 1- Modify GPA()
1- Modify GPA()
2- Change Study level ()
1- Modify GPA() 2- Change Study level () 3- Get Student Name ()
2- Change Study level () 4- Get Student Address () 4- Get Student Address ()
3- Get Student Name ()
4- Get Student Address ()
What is Class ? Why we need It ?
Student 1 Student 3
Data: Data:
1- Student_name 1- Student_name
2- University_Id 2- University_Id
3- Birth_Date 3- Birth_Date
4- Address 4- Address
Class Student 5-GPA 5-GPA
6- Study_Level 6- Study_Level
Operations ( ) Operations ( )
Data: 1- Modify GPA() 1- Modify GPA()
1- Student_name , 2- Change Study level () 2- Change Study level ()
3- Get Student Name () 3- Get Student Name ()
2- University_Id 4- Get Student Address () 4- Get Student Address ()
3- Birth_Date
4- Address
5-GPA Student 2
6- Study_Level Data:
1- Student_name
Operations ( ) 2- University_Id
3- Birth_Date
1- Modify GPA() 4- Address
2- Change Study level () 5-GPA
6- Study_Level
3- Get Student Name ()
4- Get Student Address () Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student Address ()
What is Class ? Why we need It ?
Student 1 Student 3
Data: Data:
1- Student_name
1- Student_name
2- University_Id
Class Student 3- Birth_Date
2- University_Id
3- Birth_Date
4- Address
4- Address
5-GPA
5-GPA
6- Study_Level
Data: 7- Email
6- Study_Level
7- Email
1- Student_name , Operations ( )
2- University_Id Operations ( )
1- Modify GPA()
1- Modify GPA()
3- Birth_Date 2- Change Study level ()
2- Change Study level ()
3- Get Student Name ()
4- Address 4- Get Student Address ()
3- Get Student Name ()
5-GPA 4- Get Student Address ()
5- Print Student Info ()
5- Print Student Info ()
6- Study_Level
7- Email Student 2
Data:
Operations ( ) 1- Student_name
2- University_Id
1- Modify GPA() 3- Birth_Date
2- Change Study level () 4- Address
3- Get Student Name () 5-GPA
6- Study_Level
4- Get Student Address ()
5- Print Student Info () 7- Email
Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student Address ()
5- Print Student Info ()
What is Class ? Why we need It ?
Student
Class Student
1
Data:
1- Student_name , = Ahmed
2- University_Id = 1050
5-GPA =3.75
6- Study_Level =5
Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student GPA ()
Objects and Classes
• Classes: Where Objects Come From
– A class is code that describes a particular type of object. It specifies the
data that an object can hold (the object's fields), and the actions that an
object can perform (the object's methods).
– You can think of a class as a code "blueprint" that can be used to create
a particular type of object.
Objects and Classes
• When a program is running, it can use the class to create, in
memory, as many objects of a specific type as needed.
Student
Class Student
1
Data:
1- Student_name , = Ahmed
2- University_Id = 1050
5-GPA =3.75
6- Study_Level =5
Operations ( )
1- Modify GPA()
2- Change Study level ()
3- Get Student Name ()
4- Get Student GPA ()
Writing a Class, Step by Step
• A Rectangle object will have the following fields:
Rectangle
length
width
setLength()
setWidth()
getLength()
getWidth()
getArea()
Writing the Code Rectangle
Public:
void setLength(float len)
{
If (len >=0)
length = len;
Else cout<<“Error , Please Enter positive value”;
}
}
Create Your First Class
Part 2
class Rectangle Rectangle
{ - width : float
private: - length : float
float length; + setWidth(w : float) : void
float width; + setLength(len : float): void
+ getWidth() : float
+ getLength() : float
Public: + getArea() : float
void setLength(float len)
{
If (len >=0)
length = len;
Else cout <<“Error , Please Enter positive value”;
}
}
Creating a Rectangle object
Rectangle box; Int X; String name;
A Rectangle object
The box
variable holds length: 0.0
the address of address
the Rectangle width: 0.0
object.
Create Your First Class
Part 3
More Examples
Setter , Mutator
Getter, Accessor
Separating Class Code into 2 files.
The class code can be separated into 2 files:
Header File - .h
Client Code
• client code, is the one that includes the main function. This file should be stored by the name main.cpp
public class Rectangle
{ float getArea()
private: {
return length * width;
float width; }
float length; }
public :
void setWidth(float w)
{ width = w;
}
void setLength(float len)
{ length = len;
}
float getWidth()
{ return width;
}
float getLength()
{ return length;
}
Instance Fields and Methods
public :
Rectangle( )
{
length = 0;
width = 0;
}
Constructor & Destructor
Part 2
Constructors – Initialization list
public :
Rectangle( ): length(0), Width (0)
{
Cout <<“The Rectangle Length and width are initialized”;
}
public :
public :
Rectangle(float len, float w)
Rectangle(float len, float ):
{ length(len),width(w)
length = len; {
width = w; }
}
Destructor
• A destructor is a special method that is automatically called when an object
life time is ended.
public :
~Rectangle( )
{
}
Method and Constructor
Overloading – Part 1
Overloading Methods and Constructors
• Two or more methods in a class may have the same name as long as
their signatures are different.
• Method signature (No of Args – Types of Args – Order of Args)
• When this occurs, it is called method overloading. This also applies
to constructors.
• Method overloading is important because sometimes you need
several different ways to perform the same operation.
Overloaded Method add
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
Rectangle box1();
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Default Copy Constructor
The Default Copy Constructor
- It is another way to initialize an object:
- Used to initialize an object with another object of the same type.
- No need to create a special constructor for this; one is already built into all classes
int feet; {
float inches; Distance d1;
public Rectangle()
{
length = 1.0;
width = 1.0;
}
Passing Objects to Methods
Passing Objects as Arguments
• Objects can be passed to methods as arguments.
• When an object is passed as an argument, the value of the reference variable is passed.
• The value of the reference variable is an address or reference to the object in memory.
• When a method receives a reference variable as an argument, it is possible for the method
to modify the contents of the object referenced by the variable.
Class Calculator Main()
{ {
Float add(float num1, float num2) Calculator calc;
{ Float x = 50.0 ;
return num1 + num2; Float Y = 10.0;
}
Calc.add (x , y);
string add(string a, string b)
{ }
return a + " " + b;
}
}
~Distance ( )
Feet = 8
Inches = 7.75
Result
Static Class Members
Static Class Members
• Static fields and static methods do not belong to a single instance of a class.
• A static data item is useful when all objects of the same class must share a
common item of information.
• Its lifetime is the entire program. It continues to exist even if there are no
objects of the class.
• To invoke a static method or a static field, use the class name, rather than
the instance name.
class Car int Car::count = 0;
{
int main()
string Maker ; {
Car c1, c2, c3; //create three objects
int model ;
cout << “count is “ << c1.getcount() << endl;
static int count;
cout << “count is “ << c2.getcount() << endl;
public: cout << “count is “ << c3.getcount() << endl;
Car( ) //increments count when object created return 0;
{ count++; } }
int getcount( ) //returns count
{ return count; }
};
Static Fields
instanceCount field
(static)
c= a + b ;
c3 = c1+ c2;
//Operator Overloading
++c1; //increment c1
++c2; //increment c2
++c2; //increment c2
F=5 + F=4 = F= 9
D1 D2 Result
Inheritance – Part 1
What is Inheritance?
• Inheritance is probably the most powerful feature of object-oriented
programming, after classes themselves.
• Inheritance is the process of creating new classes, called derived classes, from
existing or base classes
• The derived class inherits all the capabilities of the base class but can add its
own features. And the base class is unchanged by this process.
• Inheritance permits code reusability.
int main()
{
CountDn c1; //c1 of class CountDn
• Unlike other object oriented programming languages, C++ allow this important features
to programmers.
Polymorphism – Virtual Functions
What is Polymorphism ?
• Polymorphism is an object-oriented programming concept that
refers to the ability of a variable, function or object to take
on multiple forms.
• with polymorphism, class objects belonging to the same hierarchical tree
(inherited from a common parent class) may have functions with the same
name, but with different behaviors.
Shape
String : Color
Draw ( )
Erase ( )
Get_area ( )
Shape
String : Color
Get_area ( )
• Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
Shape Shape* shap_ptr ;
String : Color
Draw ( )
Erase ( )
Get_area ( )
shap_ptr
Rectangle R;
Box B ; Circle C ;
Sales Engineer
Float : Goss_Sales String : Speciality
Float : Commission_Rate Int : Experience
Set_Gross_Sales( ) int: overtime_hours
Set_commission_Rate ( ) Float:overtime_hour_rate
Set_OverTime_Hours( )
Set_OverTime_hour_rate ( )
Exception Handling
Introduction
• Exceptions
– Indicate problems that occur during a program’s execution
– A C++ exception is a response to an exceptional circumstance that arises
while a program is running, such as an attempt to divide by zero.
• Exception handling
– Can resolve exceptions
• Allow a program to continue executing or
• Notify the user of the problem and
• Terminate the program in a controlled manner
– Makes programs robust and fault-tolerant
Exception Handling
• An exception is a class
• Usually derived from one of the system’s exception base classes
• Exception Class is the standard C++ base class for all exceptions
• Provides derived classes with virtual function what()
– Returns the exception’s stored error message
• try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch ( ) {
// Block of code to handle errors
}
Exception Handling
try {
// code to try
}
catch (exceptionClass1 &name1) {
// handle exceptions of exceptionClass1
} catch clauses attempted
in order; first match wins!
catch (exceptionClass2 &name2) {
// handle exceptions of exceptionClass2
}