Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ private array initialization in the header file

I have a class called Cal and it's .cpp and .h counterpart

Headerfile has

class Cal {
    private:
        int wa[2][2];

    public:
        void do_cal();
};

.cpp file has

#include "Cal.h"
void Cal::do_cal() {
   print(wa) // where print just itterates and prints the elements in wa
}

My question is how do I initialize the array wa ? I just can't seem to get it to work.

I tried with :

int wa[2][2] = {
                {5,2},
                {7,9}
               };

in the header file but I get errors saying I cant do so as it's against iso..something.

Tried also to initialize the array wa in the constructor but that didnt work either.. What am I missing ?

Thanks

like image 933
Milan Avatar asked Nov 29 '22 07:11

Milan


2 Answers

If it can be static, you can initialize it in your .cpp file. Add the static keyword in the class declaration:

class Cal {
    private:
        static int wa[2][2];
    public:
        void do_cal();
};

and at file scope in the .cpp file add:

#include "Cal.h"
int Cal::wa[2][2] = { {5,2}, {7,9} };
void Cal::do_cal() {
   print(wa) // where print just itterates and prints the elements in wa
}

If you never change it, this would work well (along with making it const). You only get one that's shared with each instance of your class though.

like image 121
Rob K Avatar answered Dec 05 '22 10:12

Rob K


You cannot initialize array elements in a class declaration. I recently tried to find a way to do just that. From what I learned, you have to do it in your initialize function, one element at a time.

Cal::Cal{
   wa[0][0] = 5;
   wa[0][1] = 2;
   wa[1][0] = 7;
   wa[1][1] = 9;
}

It's possible (and probable) that there's a much better way to do this, but from my research last week, this is how to do it with a multi dimensional array. I'm interested if anyone has a better method.

like image 27
Perchik Avatar answered Dec 05 '22 11:12

Perchik