In OO parlance, the term method is used to denote a function within a class.
If a class 's methods were to become increasingly large it could make the code difficult to read, and it is therefore common practice to declare prototypes for the methods inline (i.e. within the class) and to then define the implementation of the methods outside of the class's body, to then be accessed using the :: scope resolution operator.
#include <iostream> using namespace std ; class Triangle { private: float width ; float height ; public: void setWidth(float) ; //setter prototype void setHeight(float) ; float getWidth() ; //getter prototype float getHeight() ; float area() ; //method prototype } ; void Triangle::setWidth(float x){ //REMEMBER TO DECLARE RETURN TYPE width = x ; } void Triangle::setHeight(float y){ //REMEMBER TO DECLARE RETURN TYPE height = y ; } float Triangle::getWidth(){ //REMEMBER TO DECLARE RETURN TYPE return width ; } float Triangle::getHeight(){ //REMEMBER TO DECLARE RETURN TYPE return height ; } float Triangle::area(){ //REMEMBER TO DECLARE RETURN TYPE return ((width * height) / 2) ; } int main () { Triangle myTriangle ; myTriangle.setWidth(12) ; myTriangle.setHeight(2000) ; cout << "myTriangle width was set at " << myTriangle.getWidth() << endl ; cout << "myTriangle height was set at " << myTriangle.getHeight() << endl ; cout << "myTriangle area: " << myTriangle.area() << endl ; return 0; }
Compile & Run:
myTriangle width was set at 12 myTriangle height was set at 2000 myTriangle area: 12000 |