You are on page 1of 18

Introduction to Object Oriented Programming

OOP programs can be viewed as a collection of interacting objects. The objects in 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: Real-life problems are unclear and the first thing you have to do is to try to understand the problem to separate necessary from unnecessary details. This process of modeling is called abstraction and is illustrated below.

Problem Abstraction

Model The model defines an abstract view to the problem. This implies that the model focuses only on problem related stuff that define properties of the problem. These properties include the data which are affected and the operations which are identified by the problem.

Abstract Data Types


Each ADT description consists of two parts i) Data: This part describes the structure of the data used in the ADT in an informal way. ii) Operations: This part describes valid operations for the ADT, hence it describes its interface. The constructor is used to describe the operations to be performed once an entity of the ADT is Object Oriented Programming Notes ~ Wainaina Page 1 of 18

created while a destructor is used to describe the actions to be performed once an entity is destroyed Note: since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT)

Abstract Data Types and Object-Orientation


ADTs allows the creation of instances with well-defined properties and behaviour. In object-orientation ADTs are referred to as classes . Therefore a class defines properties of objects which are the instances in an objectoriented environment.

Definitions:
A class is the implementation of an abstract data type (ADT). It defines attributes and methods which implement the data structure and operations of the ADT, respectively. 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. A method is associated with a class. An object invokes a method as a reaction to receipt of a message. 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: class TagName // head { // data declaration // operations declaration }; //definition is now complete A declaration of a class type uses just the head of the definition. Class TagName;

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.

Object Oriented Programming Notes ~ Wainaina

Page 2 of 18

Specifying the Access Region class A{ private: // this is optional since private is default private members declared here public: public members here };

Defining Member Functions within the Class Definition


When a member function is defined within the class definition, it is implicitly inlined, however, it is more common to define the member functions outside of the class definition. Example Using the concept of a class, write a C++ program that accepts and displays an integer number //method one #include <iostream> using namespace std; class Numbers { int i; public: void setValue (int value_in) {i=value_in;} int getValue (void) {return i;} }; int main () { Numbers num; int x; cout << "Enter an integer number" <<endl; cin >> x; num.setValue (x); cout << "You entered " << num.getValue() <<endl; return 0; } //method two #include <iostream> using namespace std; class Numbers{ int i; public: inline void setvalue(int); inline int getvalue(); }; void Numbers::setvalue(int value_in){i=value_in;} int Numbers::getvalue(){return i;} int main() { Object Oriented Programming Notes ~ Wainaina Page 3 of 18

Numbers num; int x; cout<<"Enter an integer number:"<<endl; cin>>x; num.setvalue(x); cout<<"You entered:" <<num.getvalue()<<endl; return 0; }

Defining Member Functions outside the Class Definition


When member functions are defined outside the class definition, you need to use the class scope quantifier (::) at the point of definition. The left operand of the:: operator is the class name to which the function belongs, while the right operand is the identifier of the function.

Example
i). Create a C++ class for a rectangle abstract data type. The class has attribute length and width. It has member functions that calculate the area and perimeter of rectangle. It has set and get member functions for both length and width. The set function should verify that the length and width are each floating point numbers between 0 and 20, non-inclusive. ii). Write a driver program that uses the class above to find the area and perimeter of the rectangle. #include <iostream> using namespace std; //class definition (Part one) class Rectangle { public: void setLength (float); void setWidth (float); float getLength (void); float getWidth (void); float Perimeter (void); float Area (void); private: float length, width; }; //member function definition void Rectangle::setLength (float l) {length=l;} void Rectangle::setWidth (float w) {width=w;} float Rectangle::getLength (void) {return length;} float Rectangle::getWidth (void) {return width;} float Rectangle::Area (void) {return length*width;} float Rectangle::Perimeter (void) {return 2*(length+width);}

Object Oriented Programming Notes ~ Wainaina

Page 4 of 18

//driver program (Part Two) int main () { Rectangle rec; float length, width; cout << "Enter the length and width of the rectangle" <<endl; cin >> length >> width; rec.setLength(length); rec.setWidth(width); system("cls"); cout<<"For rectangle of length: " << rec.getLength () <<" and width: "<< rec.getWidth() <<endl <<"has an area of: "<<rec.Area () <<endl <<"and a perimeter of: "<<rec.Perimeter ()<<endl; return 0; } this Pointer The this pointer is an implicit (hidden) first argument to member functions. It holds the address of the object to be accessed. It is automatically dereferenced to properly access an object's members. Example void Date:: Display(void) { cout << day << endl; cout << mon << endl; } becomes: void Date :: Display (Date * this) { cout << this->day << endl; cout << this->mon << endl; } and: Date day; day.display(); becomes: Date day; Date::display(&day); Note : this is a reserved word in C++. Sometimes it is necessary to use the this pointer explicitly within a member

Object Oriented Programming Notes ~ Wainaina

Page 5 of 18

EXAMPLE

#include <iostream> using namespace std; class Date { int mon; int day; public: void setDate(int d, int m) {day = d; mon = m;} void Display () {cout<<day<<"/"<<mon<<endl;} void which_day (); }; void Date::which_day() { int day = 15; cout<<"(local initialized variable) :"<<day<<endl; cout<<"(class data member) :"<<this->day<<endl; } int main() { Date today; today.setDate(20,10); today.which_day(); return 0; } Output (local initialized variable): 15 (class data member): 20

Exercises
1. i). Create a C++ class for a simple four-function calculator and which can be used to calculate for the product, quotient, sum and difference of any two integers. ii). Write a driver program that implements the above class. Your program should input two numbers and an operator and calculate for either sum, product, quotient or difference depending on operator entered. The program should print out values entered, operator and computed value in a suitable format. 2. Using the concept of a class, write a C++ program that can be used by the university library to do the following: i). Allow books codes and names to be entered and stored for all books in the library. ii). Allow the librarian to display on the screen all the books and codes in the library in a suitable format after entering a command. (Assume the library has five thousand books)

Object Oriented Programming Notes ~ Wainaina

Page 6 of 18

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 i). Default constructor Is a constructor that takes no arguments/parameters and performs no processing other than the reservation of the memory. The default constructor is always called by the compiler if no other user defined constructor is provided. Usually it is not referred by the programmer in the class definition. ii). User-defined constructor It is a constructor method defined explicitly if parameters or initialization processing are required when an object is created. It is possible to have more than one constructor in a class provided that the difference versions are defined by differences in the parameter list (i.e. constructor overloading) iii). Copy Constructor It is a constructor that allows initialization. Examples of initialization are: an object is declared and initialised with the contents of another existing object. an object is passed as a parameter to a function. E.g. The following illustrates a copy constructor, which passes only one parameter which is the object that it is going to be used to copy. Note that the object is passed by constant reference because it should not be changed. Construct::Construct (const Construct &rv) { a=rv.a; b=rv.b; c=rv.c; } The object is created as follows using the copy constructor created above Construct a(12,14,16); //create object a using a user-defined constructor Object Oriented Programming Notes ~ Wainaina Page 7 of 18

Construct b(a); //create object b using a copy constructor Construct *c = new Construct (b); // copy constructor 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. Solution #include<iostream> #include<iomanip> #include<cstring> #include<cstdlib> using namespace std; class BankAccount{ public: //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 { Object Oriented Programming Notes ~ Wainaina Page 8 of 18

return account_number; } char* BankAccount::getAccountHolder() { return account_holder; } double BankAccount::getCurrentBalance()const { return current_balance; } void BankAccount::setAccountNumber(int number) { account_number=number; } 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) { Object Oriented Programming Notes ~ Wainaina Page 9 of 18

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); } cout<<"\nDisplay the account details"<<endl; cout<<"Account number is :"<<client.getAccountNumber()<<endl; cout<<"Account Holder is : "<<client.getAccountHolder()<<endl; cout<<"The Current Balance is : "<<client.getCurrentBalance() <<endl; return 0; } 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: BankAccount client= BankAccount(10000); //explicit call BankAccount client(10000); // implicit call 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. Constructor Initialization List The initialization list is used in a constructor for initializing object members data. E.g. the following constructor can be written as follows using the constructor initialization list // Constructor class Rectangle{ int length,width; Rectangle(int l, int w) { length=l; width=w; } }; Object Oriented Programming Notes ~ Wainaina Page 10 of 18

// using constructor initialization list class Rectangle{ int length,width; Rectangle(int l, int w): length(l), width(w){} }; Note The initialisation list syntax is required when class data members are: i). constant data type ii). reference data type iii). another class object that has a constructor and either the constructor requires parameters or we want to override the default values. 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() Object Oriented Programming Notes ~ Wainaina Page 11 of 18

{ delete length; delete width; } 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; }

Constant Member Functions


These are member functions (methods) that cannot change the value of any member of the class. Constant member functions are defined using the keyword const, which is placed in the header of the member function. Syntax return_type function_name (parameter list) const { Statement (s) }

Static Data Members


A data member of a class can be qualified as static. The properties of a static member variable are as follows: It is initialized to zero when the object of the class is created. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created. It is visible only within the class, but its lifetime is the entire program. Generally they are used to maintain values common to the entire class. E.g. a static data member can be used as a counter that records the occurrences of all the objects an illustrated by the following program: #include<iostream> #include<iomanip> using namespace std; class Item { static int count; int number; public: void getData(int a){ number=a; count++; } void getCount(){ cout<<"Count:"<<count<<endl; } Object Oriented Programming Notes ~ Wainaina Page 12 of 18

}; //definition of the static data member int Item::count; int main() { Item a,b,c; a.getCount(); b.getCount(); c.getCount(); a.getData(100); b.getData(200); c.getData(300); cout<<"After reading data"<<endl; a.getCount(); b.getCount(); c.getCount(); return 0; } /* end of main */ Expected output from the program: 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

Static Data Functions


They have the following characteristics: i) Can have access to only static members (data or functions) declared in the same class. ii) Member functions can be called using class name (instead of objects) as follows: class_name::function_name 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. Object Oriented Programming Notes ~ Wainaina Page 13 of 18

#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: Count: 2 Count: 3 Object number: 1 Object number: 2 Object number: 3 Note that code=++count; is executed whenever setCode() is invoked and the current value of count is assigned to code. Since each object has its own copy of code, then the value it contains represents a unique number of its object.

Object Oriented Programming Notes ~ Wainaina

Page 14 of 18

Separating Interface from Implementation


One fundamental principals of good software engineer is to separate interface from implementation. This make it easier to modify programs. I.e. changes in class implementation do not affect the client as long as the class interface originally provided to the client is uncharged. When splitting a program into multiple files, each class definition and class member definitions are placed in the header file. The header file are included (via # include) in each file in which the class is used. 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> #include<cstring> #include"salesperson.h" using namespace std; SalesPerson::SalesPerson() { for(int i=0;i<12;i++) sales[i]=0; } void SalesPerson::getSalesFromUser() { double sales_figure; for(int i=1;i<=12;i++) { Object Oriented Programming Notes ~ Wainaina Page 15 of 18

cout<<"Enter the sales amount for month "<<i<<":"; cin>>sales_figure; setSales(i,sales_figure); } } void SalesPerson::setSales(int month,double amount) { if(month>=1 && month<=12 && amount>0) sales[month-1]=amount; else cout<<"Invalid month or sales valus"<<endl; } void SalesPerson::printAnnualSales() { cout<<"The total amount sales are KSh: " <<totalAnnualSales()<<endl; } double SalesPerson::totalAnnualSales() { double total=0; for(int i=0;i<12;i++) total+=sales[i]; return total; } //defines the main function implementation of the program #include"SalesPerson.h" int main() { SalesPerson sales; sales.getSalesFromUser(); sales.printAnnualSales(); return 0; }

Friend Functions and Friend classes


A friend function of a class is a function which is defined outside the class scope yet it has the right to access private member of that class .A function or an entire class may be declared to be a friend of another class. Friend functions are commonly used with operator overloading, or when a function needs to access objects in two separate classes. 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> Object Oriented Programming Notes ~ Wainaina Page 16 of 18

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; }; // Friend function defination double Mean(Sample & s) { return (s.a+s.b)/2; } // main function defination int main() { Sample X; X.getValues(); //call the friend function cout<<"The mean value is:"<<Mean(X)<<endl; return 0; } Note A class can also be a friend to another class. All the functions in the friend class can access the private elements of another class. This is useful when class objects are managed by another class. E.g. the following declaration makes an entire class to be a friend of another class. friend class Otherclass; // all member functions in Otherclass are friends Syntax: class A{ .. . type fun1(); // member function of X ... }; class B{ .. friend class A; // all member functions of A are friends to B }; Object Oriented Programming Notes ~ Wainaina Page 17 of 18

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 &); }; void Max(XYZ & m, ABC & n) // definition of friend { if (m.x>=n.a) cout<<m.x<<endl; else cout<<n.a<<endl; } int main() { ABC abc; abc.setValue(10); XYZ xyz; xyz.setValue(20); Max(xyz,abc); return 0; }

Object Oriented Programming Notes ~ Wainaina

Page 18 of 18

You might also like