Procedural to OOP
Encyclopedia : P : PR : PRO : Procedural to OOP
The following example uses C and C++ to demonstrate how Procedural program code could be translated to Object-Oriented program code.
Encapsulation
C code
//////////////////////////////////////////////////////// // // // The following code uses a PROCEDURAL paradigm // // to calculate the area and perimeter of a circle. // // // ////////////////////////////////////////////////////////#define PI 3.14159265359 #include
double circle_area(double r)
double circle_perimeter(double r)
int main()
Equivalent C++ code
In an Object-Oriented language like C++, we can create a circle class and encapsulate the same procedures within...
/////////////////////////////////////////////////////////// // // // The following code uses an OBJECT-ORIENTED paradigm // // to calculate the area and perimeter of a circle. // // // ///////////////////////////////////////////////////////////#define PI 3.14159265359 #include
using namespace std; class Circle // Encapsulated procedure double circle_perimeter() // Encapsulated procedure
public: Circle(double r) // Constructor
double GetArea() // Public interface to find the area double GetPerimeter() // Public interface to find the perimeter }
int main()
Inference
As can be seen from the example above the - procedural functions become the public or private method of class 'Circle' - the variables defined in main, global variables may become public or private variables in class 'Circle'Inheritance
During 'Inheritance' one may declare common methods area(), perimeter() and variables in class 'shape' which may be parent of class circle, square and triangle etc.Polymorphism
An array of 'shape' objects may, for example, contain objects of types 'circle', 'square' and 'triangle'
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
