91. Basics of Classes

Question.6

A C struct for a circular buffer:

struct CBuf { uint8_t buf[64]; int head; int tail; };

A user writes cbuf.head = 999; -- no bounds check, buffer corrupted.

A C++ class version:

class CBuf {
   uint8_t buf[64];
   int head = 0, tail = 0;
public:
   bool push(uint8_t val) {
       if (is_full()) return false;
       buf[head] = val;
       head = (head + 1) % 64;
       return true;
   }
};

What does the class version prevent?

Need Help? Refer to the Quick Guide below

Select Answer