Methods¶
Objects - Data and Methods¶
C
Object ⇔
struct
Operations on objects: free functions
⟶ can be defined anywhere
struct point p = {1,2}; point_move(&p, 3, 4); // <--- not syntactically *bound* to p
C++
Classes: data and methods
Methods: functions bound to objects
point p{1,2}; p.move(3,4);
class point
Again¶
Reiterating class point
from
Classes and Objects:
What is a point? ⟶
x
andy
What is the responsibility of a point?
move itself
compute its distance to origin
… or from another point …
#ifndef POINT_H
#define POINT_H
#include <cmath>
class point
{
public:
point() = default; // since C++ 11
point(int x, int y) : _x(x), _y(y) {}
// access methods ("getters")
int x() { return _x; }
int y() { return _y; }
void move(int x, int y)
{
_x += x;
_y += y;
}
double distance(point other)
{
auto a = std::fabs(_x - other._x);
auto b = std::fabs(_y - other._y);
auto c = std::sqrt(std::pow(a, 2) + std::pow(b, 2));
return c;
}
double distance_origin()
{
return distance(point{0,0});
}
private:
int _x{}; // since C++ 11
int _y{}; // since C++ 11
};
#endif
Simple Methods: Access Methods (“Getters”)¶
Members are private ⟶ outside access prohibited
Read-only access desired, though
⟶ Public access methods
class point
{
public:
int x() const { return _x; }
int y() const { return _y; }
private:
int _x;
int _y;
};
const
: read-only access does not alter the objectconst point p{1,2}; int x = p.x(); // <--- x() is *const* => ok
How Are Members Accessed Inside Methods?¶
Method is a function that is defined inside the class definition
⟶ C++ knows that an object is involved
_x
in method body means: “the_x
of the object”Accessed via the hidded
this
pointer (see this)
const
Methods¶
Getters above are
const
but trivialEven non-trivial methods can be
const
⟶ whenever a method does not modify a member, it should be written as
const
class point
{
public:
double abs() const
{
int hyp = _x*_x + _y*_y; // <--- read-only member access -> const
return sqrt(hyp);
}
};
Non const
Methods¶
Moving a point obviously must modify its coordinates
⟶ cannot be
const
class point
{
public:
void move(int x, int y)
{
_x += x;
_y += y;
}
};
Non
const
methods cannot be called on objects that areconst
⟶ that is the deal, after all
const point p{1,2};
p.move(3,4); // <--- ERROR: passing ‘const point’ as ‘this’ argument discards qualifiers
Error message is a little “C++ standardese”