Object-Oriented Programming is a way to integrate with objects that might contain data (in the form of attributes or properties of objects), and code blocks in the form of procedures (methods, functions of objects). These attributes and methods are variables and functions that belong to the class, they are generally referred to as class members. Do you want to learn how to define a method in a class, inside a class, or outside of a class? Here we go,
A Method in a Class is a function that operates inside or outside of this belonging class. Methods are defined in a class in two ways, Inside of the class or at the outside of the class. Let’s see them,
1. Defining a Method Inside a Class
In this method, we will declare and define a method inside the class. Let’s define a THuman Class for a human and let’s define an Info() method inside a class that tells what it is,
Note that here THuman is a class and info() is the method of this class. Any objects created by this class example will have all properties and methods of this class including this info() method. We can use this class to create a new object from this class and we can get information from this class by using its info() method as in this full example below,
2. Defining a Method Outside of a Class
In this method we will define a method outside of the class and we will include its declaration inside of the class. If you want to learn more about definition and declaration in functions please see our previous post. As in example below, now let’s define our function outside. To do this we should declare it inside the Class as below,
Now our class has info function, but this function has no definition, we need a codeblock , statement that tells what this function will do. To define this function as a member of this class we should use ‘::’ operator to point this function is a method of that class. In a general form, a function, a method of class should be described by using ‘::’ operator, as given in below,
Thus, our info() method should be declared and defined outside like this,
This below is the full example of method declaration outside of a Class,
3. Defining a Method with Parameters Inside a Class
We can define a info() method with a parameter inside a class, This example below prints out the name given in this info() function,
4. Defining a Method with Parameters Outside of a Class
We can define a info() method with a parameter outside of a class, This example below prints out the name given in this info() function,