-3

I am attempting to implement a circular buffer. So now I am testing some code.

raw_buffer.h

#include <algorithm> // for std::min

#ifndef RAWBUFFER_H
#define RAWBUFFER_H

class CircularBuffer
{
public:
    CircularBuffer(size_t capacity);
    ~CircularBuffer();

    size_t size() const { return size_; }
    size_t capacity() const { return capacity_; }
    // Return number of bytes written.
    size_t write(const char *data, size_t bytes);
    // Return number of bytes read.
    size_t read(char *data, size_t bytes);

private:
    size_t beg_index_, end_index_, size_, capacity_;
    char *data_;
};

extern CircularBuffer MyCircularBuffer;

#endif

main_raw.cpp

#include "raw_buffer.h"
#include <iostream>
#include <string>   

using namespace std;

    int main() {
        const char *data_test1 = "AAAA";
        const char *data_test2 = "BBBB";
        const char *data_test3 = "CCCC";

        CircularBuffer Buffer;//<---error

        return 0;
    }

The line CircularBuffer Buffer; is giving me the error: "no default constructor exists for class "CircularBuffer".

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
jdscardoso
  • 291
  • 3
  • 17

2 Answers2

5

When you defined this parameterized constructor, you disabled the compiler generated default constructor

CircularBuffer(size_t capacity);

You can add the following to get the default constructor back (note that the default keyword is new as of C++11)

CircularBuffer() = default;

Though you should make sure that your class is instantiated in a valid state. If default initialized values do not fit the bill, then you should manually define the default constructor to initialize your member variables to a valid state.

If you intended to call your parameterized constructor, then you need to pass the argument that you declared. E.g.

CircularBuffer buffer{10};   // constructed with a capacity of 10
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 4
    It's unlikely a defaulted default ctor is the right solution here. You'd leave `capacity_` uninitialised... Are you sure this is good advice? – Lightness Races in Orbit Jul 20 '15 at 14:35
  • That is a good point, but I cannot answer that for the OP. They should either not use the default constructor if it doesn't make sense for this class, or use the compiler generated default, or define a default constructor that *does* leave the class in a valid state. Which they choose is up to them. – Cory Kramer Jul 20 '15 at 14:38
  • In general I agree but it is as least clear that leaving a member uninitialised after construction is a bad idea, which is unavoidable with your suggestion of `= default`. – Lightness Races in Orbit Jul 20 '15 at 14:41
3

As @CoryKramer answered you didn t get a default constructor. If you want to change it you can also do this:

CircularBuffer(size_t capacity = 0);

by default if no capacity is send it will be are 0.