Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass a class member's fixed size array by reference?

I have a class Node that contains a fixed-size array. I have another class that creates an instance myNode and calls a function to assign 5 values to the fields in the array. I want to pass the array by reference so the function modifies the actual array and not a copy, but I can’t figure out how.

Node:

class Node
{
public:
    // Constructor, destructor, other members, etc
    uint8_t mArray[5];
}

Worker:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class worker
{
    void doStuff(uint8_t (&arr)[5])
    {
        arr[0] = 12;
        arr[1] = 34;
        arr[2] = 56;
        arr[3] = 78;
        arr[4] = 90;
    }

    int main()
    {
        Node *myNode = new Node();
        doStuff(myNode->mArray);
        // myNode->mArray is not modified
    }
}

>Solution :

Yes, the array is modified. A minimal reproducible example:

#include <cstdint>
#include <iostream>

class Node {
public:
    uint8_t mArray[5];
};

class worker {
    void doStuff(uint8_t (&arr)[5]) {
        arr[0] = 12;
        arr[1] = 34;
        arr[2] = 56;
        arr[3] = 78;
        arr[4] = 90;
    }

public:
    int main() {
        Node *myNode = new Node();
        doStuff(myNode->mArray);
        for(auto v : myNode->mArray) {
            std::cout << static_cast<unsigned>(v) << ' ';
            std::cout << '\n';
        }
        delete myNode;
        return 0;
    }
};

int main() {
    worker w;
    return w.main();
}

This prints the expected:

12 34 56 78 90 

It’d be easier if you took a Node& in the function though:

#include <cstdint>
#include <iostream>

class Node {
public:
    uint8_t mArray[5];
};

class worker {
    void doStuff(Node& n) {
        n.mArray[0] = 12;
        n.mArray[1] = 34;
        n.mArray[2] = 56;
        n.mArray[3] = 78;
        n.mArray[4] = 90;
        // or just:
        // n = Node{12,34,56,78,90};
    }

public:
    int main() {
        Node *myNode = new Node();
        doStuff(*myNode);
        // ...
        delete myNode;
        return 0;
    }
};

int main() {
    worker w;
    return w.main();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading