The document provides an introduction to object oriented programming (OOP) compared to procedural programming. It discusses key concepts in OOP like objects, classes, attributes, methods, encapsulation. Objects contain attributes (data) and methods (behaviors). Classes are templates that define common attributes and methods for a set of objects. Encapsulation involves hiding class data and implementation details through access modifiers like private and public. Examples are provided to demonstrate how to define classes and create objects in C++ code.
Background
CIT 743
2
Ina Procedural Programming (PP), program is written in a step by
step approach. At the end of the program or subroutine, tasks get
executed in a sequential manner
PP focuses on breaking down a programming task into a collection of
variables, data structures and subroutines where the later two can
act on as many variables declared in the program.
Variables can easily be modified by any member of a program
Object Oriented Programming (OOP) focuses on breaking down a
task into units known as objects where each one includes its own
variables (data) and subroutines (methods).
PP uses subroutines and other members to act on program data
structures whereas in OOP, object subroutines act on object data
3.
CIT 743
3
Nomenclaturevaries between the two paradigms but have the same
semantics
In OOP, each object is capable of receiving messages, processing
data and sending messages to other objects
PP OOP
variable attribute
function method
argument message
module object
4.
Advantages of OOP
CIT743
4 OOP simulates real world objects thus providing easy understanding
and visualization of problems as well as the designs of the solutions.
Complexity of problems is reduced, program structures become clear.
Easy modification (maintenance) of the system. This is because objects
are interacting through public interfaces allowing modifications in their
implementations without affecting the overall performances of the
system provided that modifications do not affect their functionalities.
Modularity allows scalability of the system. More functionalities of the
system can be easily added at any time if modeled in form of objects.
Reusability of code is practiced at highest level with OOP. Objects can be
reused as many times as needed and can also be used to solve similar
problems.
Security of the program is much enhanced due to limitations of object
data from being accessed by other objects.
CIT 743
6
UsingOOP ;
o The overall program is made up of lots of different self-contained
components (objects),
o each object has a specific role in the program
o all objects can talk to each other in predefined ways.
Overview of Object and Class
Object is the smallest element of a program designed to simulate a
real world object presented by the problem.
A given problem can be broken down into unlimited number of
objects.
Each object is designed and coded independently according to what
they actually represented in a real world.
To deliver the overall program task, objects communicate through
messages.
7.
CIT 743
7
Objectshave a standard structure; must have attributes and methods
(functions).
Attributes/variables/data define specifications of objects while
methods define the functionalities offered by objects. Methods are
said to explain behaviors of objects.
Methods make use of attributes of the same object to define different
behaviors of the object.
For example
Dog
Attributes – name, age, colour, breed, etc.
Behaviour – eat, go for a walk, wiggle tail, etc.
Car
Attributes – make, engine size, colour, gear system, speed, etc
Behaviour – change gear, change speed, stop, etc.
Person
???
8.
CIT 743
8
Classis an abstract of objects or can be also defined as a collection of
objects possessing similar general properties.
Classes have similar structure as that of objects, the difference
between them being the degree of specification.
Attributes of objects carry specific values while those of classes are
assigned to either general or default ones.
Several objects can belong to the same class.
CIT 743
10
Aclass is a generic template for a set of objects with similar features.
Instance of a class = object
If class is the general (generic) representation of an object, an
instance is its concrete representation.
Another way of distinguishing classes from objects is:
A class exists at design time, i.e. when we are writing OO code to
solve problems.
An object exists at runtime when the program that we have just
coded is running.
11.
CIT 743
11
Example– address book. For each person we want to store:
Name
Age
Address
Phone number
We can write a class called Person which will represent the abstract
concept of a Person.
We will then be able to create as much Person objects as we like in
order to model our address book.
All of these objects will be an instance of our Person class.
Attributes
CIT 743
13
Thetype of the attributes could be
Any of the primitive types – int, double, boolean, …
Previously defined classes in the C++ libraries e.g String
Previously user-defined classes
We can use as many attributes as we wish
more attributes = more complex class
Example:
Person – name, age, address, DOB, phoneNo, ppsNo, …
14.
Methods
CIT 743
14
Methods(subroutines –typically functions)
a way of dividing larger programs into many smaller more
manageable segments of code each having it’s own specific task
methods performs tasks independently of each other
allows us to modularise the program
Advantages
More manageable programs
Software reusability
15.
CIT 743
15
Eachmethod has
parameters (arguments)
The parameters are local variables (accessible only within the
method)
return type
returns a value (or void)
16.
CIT 743
16
How todefine class in C++
Alternative 1: define methods implementations within the class
class Rectangle {
float width, height, area;
public:
void set_values (float a, float b) {
width = a; height = b;
}
void calcArea () {
area = width * height;
}
float getArea() {
return area;
}
};
17.
CIT 743
17
Alternative 2:define methods implementations outside the class
class Rectangle {
float width, height, area;
public:
void set_values (float, float);
void calArea () ;
float getArea();
};
void Rectangle::set_values (float a, float b) {
width = a; height = b; }
void Rectangle::calArea () {
area= width * height; }
float getArea() {
return area; }
18.
CIT 743
18
Most classesdefine a set of “set” and “get” methods to access and
modify the class variables (accessor and mutator methods)
class Person {
//attributes
string name;
int age;
string address;
string phoneNo;
// methods
public:
void setDetails (string newName, int newAge, string newAddress,
string newPhoneNo) {
name = newName; age = newAge;
address=newAdress;phoneNo=newPhoneNo;
}
19.
CIT 743
19
string getName() {
return name;
}
string getAddress () {
return address;
}
};
How are we going to return age and phoneNo?
20.
CIT 743
20
Incorporatinga class in a program
Example 1
//The program gets user’s values of width and height, calculates
rectangle //area then displays the area
#include <iostream>
using namespace std;
class Rectangle {
float width, height, area;
public:
void set_values (float a, float b) {
width = a; height = b; }
void calcArea () {
area = width * height; }
float getArea() {
return area; }
};
21.
CIT 743
21
int main(){
float w,h;
//creating an object of Rectangle
Rectangle rect;
cout<<“Enter Rectangle width:”;
cin>>w;
cout<<“Enter Rectangle height:”;
cin>>h;
//Assigning user inputs to attributes
rect.set_values(w,h);
rect.calArea();
cout<<“Area of the Rectangle is:” << rect.getArea();
system(“pause”);
return 0;
}
22.
CIT 743
22
Example 2
#include<iostream>
#include <string>
using namespace std;
class Person {
string name, address, phoneNo;
int age;
public:
void setDetails (string newName, int newAge, string newAddress,
string newPhoneNo) {
name = newName; age = newAge;
address=newAdress;phoneNo=newPhoneNo;
}
string getName () {
return name; }
string getAddress () {
return address; }
23.
CIT 743
23
int getAge() {
return age; }
string getPhone () {
return phoneNo; }
};
int main() {
string newName, newAddress,NewPhoneNo;
int newAge;
Person p;
cout<<“Enter Name:”;
cin>> newName;
cout<<“Enter Address:”;
cin>>newAddress;
cout<<“Enter Age:”;
cin>>newAge;
24.
CIT 743
24
cout<<“Enter PhoneNo:”;
cin>>newPhoneNo;
p.setDetails(newName, newAge, newAddress, newPhoneNo);
cout<<“Name of the person is:” << p.getName();
cout<<“n Address is:” << p.getAddress();
cout<<“n Age is:” << p.getAge();
cout<<“n Phone No is:” << p.getPhone();
system(“pause”);
return 0;
}
25.
CIT 743
25
Example 3
Whatif we have more than one rectangle? Lets say two
#include <iostream>
using namespace std;
class Rectangle {
float width, height, area;
public:
void set_values (float a, float b) {
width = a; height = b; }
void calcArea () {
area = width * height; }
float getArea() {
return area; }
};
26.
CIT 743
26
int main(){
float w,h;
Rectangle rect1, rect2;
cout<<“Enter width of Rectangle 1:”;
cin>>w;
cout<<“Enter height of Rectangle 1 :”;
cin>>h;
rect1.set_values(w,h);
rect1.calArea();
cout<<“Enter width of Rectangle 2:”;
cin>>w;
cout<<“Enter height of Rectangle 2 :”;
cin>>h;
rect2.set_values(w,h);
rect2.calArea();
Encapsulation
CIT 743
28
Thisrefers to the hiding of class data and its implementation details
from being exposed to objects of other classes and making data
available only through defined methods (interface).
This aims at avoiding accidental or deliberate damage of either class
data or implementations.
Allows easy modifications and testing of internal structure of a class
without affecting how users use the class as long as class outputs are
retained.
Encapsulation is achieved through access modifiers which commonly
are private , public and protected.
29.
CIT 743
29
Public;
Accessibleanywhere with elements from either the same class or not.
Private;
Accessible to only elements within the same class.
Protected will be discussed in inheritance.
30.
Constructors
CIT 743
30
Whenobject of a class is created, compiler calls for constructor for
that class. If no one was defined by programmer, compiler invokes a
default constructor it has created which only allocates memory for
the object but does not initialize attributes.
The purpose of a user-defined constructor is to initialize attributes of
an object which later can be changed to the desired specifics of that
object. Initialization avoids risks of the program in assigning garbage
(or inconsistent) values to attributes which might develop serious
bugs.
Constructor is closely similar to function with the exceptions that no
return type nor return statement. It is defined as just another
method of the class.
Name of the constructor should be the same as that of the class
31.
CIT 743
31
Thereare two types of user defined constructors; constructor with no
parameters and the one with parameters.
The first one, attributes values are determined within the class
whereas in the second one, values are determined outside the class
and therefore need to be passed as parameters.
Constructor is called when new object is created.
Consider the class below demonstrating the two constructors ( but
only one should be used in practical cases)
32.
CIT 743
32
Example 1
classPoint {
int x,y;
public:
Point() { // constructor with no parameter
x=0;
y=0;
}
Point(int new_x,int new_y) { // constructor with parameters
x=new_x;
y=new_y;
}
int getX() {
return x; }
int getY() {
return y; }
};
33.
CIT 743
33
......in themain function
Point p; //parameterless constructor is called
Point q(10,20); //constructor with no parameter is called
34.
CIT 743
34
Example 2
……………
ClassRectangle {
float width, height, area;
public:
Rectangle() { //user defined constructor with no parameters
width = 0;
height =0;
area=0; }
void set_values (float a, float b) {
width = a; height = b; }
void calArea () {
area = width * height;
}
35.
CIT 743
35
float getArea() {
return area; }
};
int main () {
int w,h;
Rectangle rect;
cout <<“Specify width and height”;
cin>>w;
cin>>h;
rect.set_values (w,h);
rect.calArea();
cout <<“n Area is:”;
cout <<rect.getArea();
….
CIT 743
37
int main() {
float w,h;
Rectangle rect(10.0,20.0);
cout <<“Specify width and height”;
cin>>w;
cin>>h;
rect.set_values (w,h);
rect.calArea();
cout <<“n Area is:”;
cout <<rect.getArea();
….
38.
CIT 743
38
Example 4
#include<iostream>
using namespace std;
class Rectangle {
float width, height
public:
Rectangle (float a, float b) {
width=a; height=b;
}
float getArea() {
return (width * height);
}
};
39.
CIT 743
39
int main() {
Rectangle recta (3.0,4.0);
Rectangle rectb (5.0,6.0);
cout << “recta area is: “ << recta.getArea() << endl;
cout << “rectb area is: “ << rectb.getArea() << endl;
…......
40.
Array of objects
CIT743
40
Objects can be regarded as any other data types and therefore can be
saved in arrays.
Example 1
#include <iostream>
using namespace std;
class Rectangle {
int width;
int height;
public:
Rectangle() {
width = height = 0; }
void set(int w, int h) {
width = w;
height = h; }
int area() {
return (width * height); }
};
41.
CIT 743
41
int itsAge;
intitsWeight;
};
int main()
{
Rectangle p[3];
p[0].set(3, 4);
p[1].set(10, 8);
p[2].set(5, 6);
for(int i=0; i < 3; i++) {
cout << "Area is " << p[i].area() << endl;
}
system(“pause”);
return 0;
}
Note the declaration of arrays of object with defined max number of
objects to be stored.
42.
CIT 743
42
Example 2
#include<iostream>
using namespace std;
class MyClass
{
public:
MyClass() {
itsAge = 1;
itsWeight=5;
}
int GetAge() {
return itsAge;
}
int GetWeight() {
return itsWeight;
}
void SetAge(int age) {
itsAge = age;
}
43.
CIT 743
43
private:
int itsAge;
intitsWeight;
};
int main()
{
MyClass myObject[5];
int i;
for (i = 0; i < 5; i++) {
myObject[i].SetAge(2*i +1); }
for (i = 0; i < 5; i++) {
cout << " #" << i+1<< ": " << myObject[i].GetAge() << endl;
}
system(“pause”);
return 0;
}