article

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) { return (PI * r * r); } double circle_perimeter(double r) { return (2 * PI * r); } int main() { double radius = 10; // The radius to use double area = 0; // The area to be found double perimeter = 0; // The perimeter to be found area = circle_area(radius); // Call a procedure to find the area perimeter = circle_perimeter(radius); // Call a procedure to find the perimeter printf("Radius:\t%4.21f\nArea:\t%4.21f\nPerimeter:\t%4.21f\n", radius, area, perimeter); return 0; }

=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 { private: double radius; // Encapsulated variable double circle_area() { return (PI * radius * radius); } // Encapsulated procedure double circle_perimeter() { return (2 * PI * radius); } // Encapsulated procedure public: Circle(double r) { radius = r; } // Constructor double GetArea() { return circle_area(); } // Public interface to find the area double GetPerimeter() { return circle_perimeter(); } // Public interface to find the perimeter } int main() { double radius = 10; // The radius to use Circle c(radius); // Instantiate an object of type Circle named 'c' with our radius cout << "Radius:\t" << radius << "\nArea:\t" << c.GetArea() << "\nPerimeter:\t" << c.GetPerimeter << endl; return 0; }

= 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'

 

This article is licensed under the GNU Free Documentation License. It uses material from the "Procedural to OOP".

Home Pageartsbusinesscomputersgameshealthhospitalshomekids & teensnewsphysiciansrecreationreferenceregionalscienceshoppingsocietysportsworld