Small Steps V — Making Your Own Types
Grouping data and operations
Group data and operations.
What you will learn
A class groups data with operations on that data. An object is an actual instance of its type. This lesson introduces the idea that you can make such tools yourself.
Try it
Example · example1.cpp
class Counter
{
public:
void add_one()
{
value = value + 1;
}
int get_value()
{
return value;
}
private:
int value = 0;
};
void small_main()
{
Counter counter;
counter.add_one();
counter.add_one();
print(counter.get_value());
}
A Counter object holds its counted value. Calling add_one twice and reading get_value() gives 2.
public exposes a part to users; private prevents direct access from outside. You have already used String and Window as objects with data and related operations. Constructors and inheritance are beyond this lesson.
Exercise
Add a public reset() to Counter that sets its value to 0, and check that it works.
Exercise starter · exercise1_starter.cpp
class Counter
{
public:
void add_one()
{
value = value + 1;
}
void reset()
{
// reset value.
}
int get_value()
{
return value;
}
private:
int value = 0;
};
void small_main()
{
Counter counter;
counter.add_one();
counter.add_one();
counter.reset();
print(counter.get_value());
}
Hint
Assign 0 to the private value inside reset.
show solution
class Counter
{
public:
void add_one()
{
value = value + 1;
}
void reset()
{
value = 0;
}
int get_value()
{
return value;
}
private:
int value = 0;
};
void small_main()
{
Counter counter;
counter.add_one();
counter.add_one();
counter.reset();
print(counter.get_value());
}