Object Oriented Programming PDF
Object Oriented Programming PDF
Object Oriented Programming PDF
OOP programs can be viewed as a collection of interacting objects. The objects this collection
react upon receipt of messages, changing their state according to invocation of methods which
might cause other messages sent to other objects. This is illustrated in below.
Object 1
Object 2
Object 4
Program Object 3
Abstraction
This refers to the act of representing essential features without including the background details
or explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as size,
weight and cost, and functions to operate on these attributes. They encapsulate all the essential
properties of the objects that are to be created. The attributes are sometimes called data members
because they hold information. The functions that operate on these data are sometimes called
methods or member functions
Note: since the classes use the concept of data abstraction, they are known as Abstract Data
Types (ADT)
An object is an instance of a class. It can be uniquely identified by its name and it defines a state
which is represented by the values of its attributes at a particular time.
The behaviour of an object is defined by the set of methods which can be applied on it.
A message is a request to an object to invoke one of its methods. A message therefore contains
the name of the method and the arguments of the method.
Attribute is a property of object. It cannot exist independently of the object. Attribute may take
other objects as values. It has a type. It describes the range of values that that property may hold.
Definition and Declaration of classes
User-defined data types must be defined before variables may be created of that type.
Definitions have the following parts:
Syntax:
// operations declaration
Access Modifiers
In order to enforce data hiding, 3 different access regions could be defined.
• Private -- only member functions of the class can access the private data.
• Public -- no restrictions to access. Functions defined anywhere have access to public
members.
• Protected -- only member functions of the class and member functions of derived
classes can access the protected data.
Constructors
Constructors are special member functions that are automatically called when an object is
created. Constructors are used to initialise the data members of the object. They provide
guaranteed initialisation of the data contained within an object declared to be of a given class.
Constructors may not be called explicitly through an object.
When using a C++ constructor, note the following important aspects:
• The declaration of the object activates the initialisation specified in the constructor.
• A constructor's identifier is the same as the class's tag name.
• Constructors may not return a value or declare any return type, not even void.
• If only one constructor is declared and it takes two arguments, you must provide two
values when declaring an object of that type. If a constructor exists, it will be invoked
when an object is declared.
The general form of a constructor is shown below:
class_name()
{
//constructor code;
}
There are three types of constructors:
i). The default constructor
ii). User-defined constructor
iii). The Copy constructor
The object is created as follows using the copy constructor created above
Example:
a). Create a C++ class that for a bank account abstract data type. It should have the attributes of
account number (an integer), account holder (a string) and current balance (a float). Define
methods to return the values of these attributes and set them using parameters. Add two
more methods to allow deposit and withdrawal updating the current balance as appropriate.
Include a constructor that enables any new account to be opened with an initial balance of
10,000 shillings.
b). Write a C++ program that implements the above class. The class should enable the user to
the following tasks.
1. Enter the name of the account holder and the account number
2. Allow the user to deposit or withdrawal by displaying an appropriate message
3. Display the user details in an appropriate form.
//Constructor
BankAccount();
//Accessor methods
int getAccountNumber()const;
char* getAccountHolder();
double getCurrentBalance()const;
void setAccountNumber(int);
void setAccoutHolder(char[],int);
void Deposit(double);
void Withdrawal(double);
private:
int account_number;
char account_holder[20];
double current_balance;
};
//Methods Defination
BankAccount::BankAccount()
{
current_balance=10000;
}
int BankAccount::getAccountNumber()const
{
return account_number;
}
char* BankAccount::getAccountHolder()
{
return account_holder;
}
double BankAccount::getCurrentBalance()const
{
return current_balance;
}
void BankAccount::setAccountNumber(int number)
{
account_number=number;
SMA2176 Computer Programming II Notes ~ A. Kamau Page 5 of 16
}
void BankAccount::setAccoutHolder(char name[],int n)
{
strncpy(account_holder,name,n-1);
account_holder[n-1]='\0';
}
void BankAccount::Deposit(double amount)
{
current_balance=current_balance+amount;
}
void BankAccount::Withdrawal(double amount)
{
current_balance=current_balance-amount;
}
//Client Program
int main()
{
char surname[20];
int account,choice;
double dep,withd;
BankAccount client;
cout<<"\nEnter the Account Number"<<endl;
cin>>account;
cout<<"\nEnter the Account holder name"<<endl;
cin>>surname;
client.setAccountNumber(account);
client.setAccoutHolder(surname,20);
system("CLS");
cout<<"Menu Operations"<<endl;
cout<<" 1 Deposit "<<endl;
cout<<" 2 Withdrawal "<<endl;
cout<<" 3 Exit"<<endl;
cout<<"\nEnter your Choice"<<endl;
cin>>choice;
if(choice==1)
{
cout<<"\n Enter amount to Deposit"<<endl;
cin>>dep;
client.Deposit(dep);
}
else
{
cout<<"\n Enter amount to Withdraw"<<endl;
cin>>withd;
client.Withdrawal(withd);
Parameterized Constructors
These are constructors that take arguments. A parameterized should be defined with parameters
and then it can either be called explicitly or implicitly as shown below:
Overloading constructors
Like any other function, a constructor can also be overloaded with several other functions that
have the same name but with different type or number of parameters.
Exercise
Write a program that has a class called circle from which two circles, c1 and c2 are created such
that c2 does not pass any argument to the constructor yet its radius value is initialized to 10 and
c1 passes 20 as the radius. The class should have an inline function to calculate the area of the
two circles which should then be displayed by the main function.
Destructors
A destructor is the compliment of a constructor. It has the same name as the constructor, but is
preceded by a tilde (~). Just like a constructor, it does not have a return type. It is automatically
called when an object is released from memory, either because its scope of existence has finished
(for example, if it was defined as a local object within a function and the function ends) or when
an object is dynamically assigned and released using operator delete.
Note that there can be no overloading of a destructor i.e. destructors may not take any arguments.
Therefore, there may be only one destructor per class.
Example
Create a class called rectangle that stores the length and width of a rectangle in two private
instance variables. Include a constructor that sets these values and a destructor which is used to
release the object created from the memory. Define a member function, display (), which returns
the area of the rectangle. Have both the object and the instance variables to be dynamically
created.
# include<iostream>
using namespace std;
class Rect
{
public:
Rect(int,int);
~Rect();
int Display(){return *length * *width;}
private:
int *length,*width;
};
Rect::Rect(int l,int w)
{
length= new int;
width=new int;
*length=l;
*width=w;
}
Rect::~Rect()
{
int main()
{
Rect *rec1=new Rect(5,4);
Rect *rec2=new Rect(4,3);
cout<<"The area of rectangle one is :"<<rec1->Display()<<endl;
cout<<"The area of rectangle one is :"<<rec2->Display()<<endl;
delete rec1;
delete rec2;
return 0;
}
a.getData(100);
b.getData(200);
c.getData(300);
Count: 0
Count: 0
Count: 0
After reading data
Count: 3
Count: 3
Count: 3
The type and scope of each static member variable must be defined outside the class definition.
This is necessary since because the static data members are stored separately rather than as a part
of an object. Since they are associated with the class itself rather with any class object, they are
also known as class variables.
From the above program, the static count is initialized to zero when the objects are created. Then
count is incremented whenever data is read into the object. Since data is read three times, count
will be incremented three times. However since only one copy of count is shared by all the three
objects, all the three output statements cause the value 3 to be displayed
Example:
The following is a C++ program that uses a static member function showCount() to display the
number of objects created at any given moment. The member function showCode displays the
code number of each object.
#include<iomanip>
using namespace std;
class Test
{
int code;
static int count;
public:
void setCode(){
code=++count;
}
void showCode(){
cout<<"Object number:"<<code<<endl;
}
static void showCount(){
cout<<"Count:"<<count<<endl;
}
};
//definition of the static data member
int Test::count;
int main()
{
Test t1,t2;
t1.setCode();
t2.setCode();
Test::showCount();//accessing static member function
Test t3; t3.setCode();
Test::showCount();
t1.showCode();
t2.showCode();
t3.showCode();
return 0;
}
Expected output:
Example
Write a complete C++ program that uses an ADT SalesPerson, with an attribute, which is an
array of twelve monthly sales figure initialized by a constructor to zero and set to user supplied
values by the member function setSales. The method printAnnuaSales prints the total sales of the
salesperson for the twelve months. The utility (helper) function totalAnnualSales totals the
twelve monthly sales for the benefit of printAnnuaSales. The printAnnuaSales should also edit
the sales figure into KSh format. Use a header file for the class definition, and separate source
files for the class member function implementation and the main function.
Solution:
//salesperson.h, defines the header file for the class definition
#ifndef SALESP_H
#define SALESP_H
class SalesPerson{
public:
SalesPerson();
void getSalesFromUser();
void setSales(int,double);
void printAnnualSales();
private:
double totalAnnualSales();
double sales[12];
};
#endif
//salesperson.cpp, defines source file for the class member function implementation
#include<iostream>
#include<iomanip>
To declare a function as a friend of a class, precede the function prototype in the class definition
with the keyword friend.
Example
Write a complete C++ program which incorporates a friend function mean that is used to
compute and return the average of two numbers contained in an object. The class has an inline
member function for inputting any two numbers. Include a main function to implement the class.
#include<iostream>
using namespace std;
class Sample
{
//Friend function declaration
friend double Mean(Sample &);
public:
void getValues(){
cout<<"Enter two numbers:"<<endl;
cin>>a>>b;
}
private:
double a,b;
};
Syntax:
class A{
…………..
………….
type fun1(); // member function of X
………...
};
class B{
…………..
friend class A; // all member functions of A are friends to B
};
Example
The following is a C++ program that demonstrates how a friend function can be used as a bridge
between two classes (i.e ability of a function to access objects in two separate classes)
#include<iostream>
#include<iomanip>
using namespace std;
class ABC;
class XYZ
{
int x;
public:
void setValue(int i){ x=i;}
friend void Max(XYZ &, ABC &);
};
class ABC
{
int a;
public:
void setValue(int i){ a=i;}
friend void Max(XYZ &, ABC &);
};
int main()
{
ABC abc;
abc.setValue(10);
XYZ xyz;
xyz.setValue(20);
Max(xyz,abc);
return 0;
}