Defining class behavior

A class can define functions that can only be called through an instance of the class; such a function is often called a method. An object will have state; this is provided by the data members defined by the class and initialized when the object is created. The methods on an object define the behavior of the object, usually acting upon the state of the object. When you design a class, you should think of the methods in this way: they describe the object doing something.

    class cartesian_vector 
{
public:
double x;
double y;
// other methods
double get_magnitude() { return std::sqrt((x * x) + (y * y)); }
};

This class has two data members, x and y, which represent the direction of a two-dimensional vector resolved in the Cartesian x and y directions. The public keyword means that any members defined after this specifier are accessible by code defined outside of the class. By default, all the members of a class are private unless you indicate otherwise. private means that the member can only be accessed by other members of the class.

This is the difference between a struct and a class: by default, members of a struct are public and by default, members of a class are private.

This class has a method called get_magnituide that will return the length of the Cartesian vector. This function acts upon the two data members of the class and returns a value. This is a type of accessor method; it gives access to the state of the object. Such a method is typical on a class, but there is no requirement that methods return values. Like functions, a method can also take parameters. The get_magnituide method can be called like this:

    cartesian_vector vec { 3.0, 4.0 }; 
double len = vec.get_magnitude(); // returns 5.0

Here a cartesian_vector object is created on the stack and list initializer syntax is used to initialize it to a value representing a vector of (3,4). The length of this vector is 5, which is the value returned by calling get_magnitude on the object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset