0

I am trying to write a function CycleManager which can hold an array of Cycles. My problem is that I want this class to be able to hold a variable amount of cycles. This is what I came up with, but it's not working.

Cycle.h

class Cycle
{
public:
    Cycle(std::string name) : name(name) {}

private:
    std::string name;
};

CycleManager.h

#include "Cycle.h"

class CycleManager
{
public:
    CycleManager(Cycle (&cycles)[]);
    void getCycles();

private:
    int currentCycle;
    int numberOfCycles;
    Cycle (&cycles)[];
};

CycleManager.cpp

CycleManager::CycleManager(Cycle (&cycles)[]) : cycles(cycles), currentCycle(0)
{
    numberOfCycles = sizeof(*cycles) / sizeof(Cycle);
}

void CycleManager::getCycles()
{
    // Serial.println(this->numberOfCycles);
    std::cout << this->numberOfCycles << std::endl;
}

Main.cpp

Cycle cycles[] = {Cycle("Cycle 1"), Cycle("Cycle 2"), Cycle("Cycle 3")};
CycleManager cycleManager(cycles);

int main()
{
    cycleManager.getCycles();
    return 0;
}
10
  • Is using arrays instead of std::vector required? Commented Jul 13, 2022 at 12:32
  • 4
    Use std::vector? Commented Jul 13, 2022 at 12:32
  • 1
    Do you know what the largest size array you could possibly need? Use that upper limit to declare the array size, and just use less of the array's maximum capacity. Commented Jul 13, 2022 at 12:40
  • 1
    I've had to work in an embedded system that had no heap, so I couldn't use std::vector. Commented Jul 13, 2022 at 12:47
  • 1
    Probably you can still use std::array, it is a bit more friendly to use when you want to pass it around and/or return arrays from functions. @OP , Next time be a bit more clear about being in an embedded system, rules change a bit then :) Commented Jul 13, 2022 at 12:48

1 Answer 1

1
Cycle cycles[] = {Cycle("Cycle 1"), Cycle("Cycle 2"), Cycle("Cycle 3")};
CycleManager cycleManager(cycles);

At this point you know the size of the array. So why not

CycleManager cycleManager(cycles, size);

Adjust constructor appropriately

CycleManager(Cycle* cycles, size_t n):cycles(cycles), numberOfCycles(n)...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.