Upload
morris-berry
View
212
Download
0
Embed Size (px)
Citation preview
Object-Oriented Programming
Procedural ProgrammingAll algorithms in a program are performed with functions and data can be
viewed and changed directly by programmer.
Object-Oriented Programming
All program can be made up as individual entity called objects. A program that is written utilizing these objects is called object-oriented program.
Each of the object used can be written by any vendor (programmer), which has a specific purpose (task).
Object can be created and deleted as it goes out of scope. Object has its own attributes and functionality.
The data in an object is not intended to be accessed directly by code that is outside of the object. This “hiding” of data is known as the term encapsulation.
// circle.h#ifndef _CIRCLE_H#define _CIRCLE_Hconst double PI=3.14159;class circle{
public:circle(); // default constructorcircle(const circle &); // copy constructorvoid SetRadius(double); // member functionsdouble Area();
private:double radius; // data
};
// default constructorcircle::circle(){
radius = 0.0;}circle::circle( const circle & obj){
radius = obj.radius;}// member functionsvoid circle::SetRadius( double R){
radius = R;}double circle::Area(){
return PI * radius * radius;}
The circle class has two constructor:• The first constructor is known as the default constructor. It is used
when the object is declared.• The second constructor is known as the copy constructor. It is used
when the object is declared with a reference to another object as an argument.
Compiler Directive:• #ifndef, #define, #endif• If is used to make sure the compiler would not define the class
definition if it has already been defined. If the compiler has gone through the code (class definition), it will skip the code the subsequent time.
18
// oop.cpp--- This object-oriented program shows the use of simple objects which represent circles.
#include "circle.h" // contains the circle class#include <iostream>using namespace std;int main(){
circle Circle_One; // declare objectscircle Circle_Two; // of type circledouble User_Radius;double Area;
cout << "\nWhat is the radius of the first circle? ";cin >> User_Radius;
// send a message to Circle_One telling it to set its radius to User_Radius
Circle_One.SetRadius(User_Radius);
18
cout << "\nWhat is the radius of the second circle? "; cin >> User_Radius;
// send a message to Circle_Two telling it to set its radius to User_RadiusCircle_Two.SetRadius(User_Radius);
// send a message to Circle_One asking for its areaArea = Circle_One.Area();
cout.setf(ios::fixed);cout << "\nThe area of the first circle is " << Area << ".\n";
// send a message to Circle_Two asking for its area cout << "\nThe area of the second circle is " << Circle_Two.Area() << ".\n";
circle Circle_Three(Circle_Two); // send a message to Circle_Two asking for its area
cout << "\nThe area of the second circle is " << Circle_Three.Area() << ".\n";
return 0;
}