Loading

C++: Member Functions

Member Functions

This C++ video covers simple member functions of a class. A member function is a function that is closely tied to an object’s data members. In fact, member functions access data members directly without using the dot operator.

Consider modeling a hamburger with a class. In this case, we will keep or hamburger simple; we can add mustard, ketchup, pickles or onions to it. Our hamburger class in this case consists of four Booleans for each additional ingredient. So, a burger with a values set to false is a plain burger.

Here, we show how we initialize a burger object with all false values—a plain burger. Then we call two member functions to add ketchup and onions to our burger. The member functions just set the corresponding Boolean values to true. We could use such a class to program order entry for a drive through at a fast food restaurant.

In our next example, we create a class to represent a rook on a chessboard. This example is a little contrived, since we probably use a more sophisticated structure in actual practice.

With our rook class below, we can move any number of spaces in the x or y directions. In actual practice, we would need to check that such moves were valid. For instance, if our movement makes our piece’s position go out of the range 0 through 7, then our piece is off the board. Likewise, we cannot jump other pieces or make other illegal moves. So, in actual practice we would need to be more careful. Here, we are merely illustrating the basic movement via simple member functions.