Call Function of Object C++ Syntax

In C++, a function object is a class object that you can use as a function. It works similarly to other functions, except you use the function call operator to pass values to the object class. For example, a function object can take a series of numbers, even if you don't know how many the user will supply when you write the code, and add them together to save the result in the class object.

  1. Use

    • To use a function object, you first define and create a object class, then create a function called "operator" as one of the public function members. If you create private member variables, you can set their value in the class constructor, then modify them with other values passed through the operator function. C++ has an advantage over similar programming language such as Java, because these other languages do not allow for operator overloading.

    Syntax

    • You create function objects similarly to any other objects in a C++ program. You define a new class, then create member variables and public and private functions as needed. However, one of the public functions you need to implement is the function call operator, which lets you use the class object in your program as a function. In the body of the program, you create function objects the same way as any other object, by typing the class name, then the object name.

    Call Operator

    • The call operator function is what makes a function object different from other class objects. Syntactically, you need to use two sets of brackets to create an operator function. For example, typing "void operator()(int val1) { total += val1; };" lets you use the object as a function to add values to a running total in a class member variable. You can then use this variable total in other class functions.

    Overloading

    • Overloading the function operator does not change how you call the function, it modifies how you pass values to the object. It lets you pass an arbitrary number of arguments, which helps if you don't know how many you need to pass at runtime. For example, if you have a class constructor that takes only two parameters and have a function call operator that takes three, you can use an existing function object to initialize a new one, but pass three parameters to it instead of two. This overloads the constructor and forces the operator function to initialize the values.

Related Searches:

References

Comments

Related Ads

Featured