Reputation: 2172
I have been working on a code in C++. But, I got stuck at a point.
This is a small prototype of my code::
#include <iostream>
using namespace std;
class Test{
private:
const int var;
void funPrivate(int arr[][var], int temp){
cout << arr[0][0] << endl;
}
public:
Test(int n) : var(n){};
void funPublic(){
int a[var][var];
funPrivate(a, var);
cout << "Hello";
};
};
int main()
{
Test t1(5);
t1.funPublic();
return 0;
}
I create a class funPublic()
method, where I create a 2D array (using the const int var, which I declare as a private member inside my class Test
) and then pass it to a private methode funPrivate(int arr[][var], int temp)
, where I print arr[0][0]
(which shall be a garbage value).
But, when I try to run this program, I get an error::
error: invalid use of non-static data member 'Test::var'
My method funPrivate(int arr[][var], int temp)
is a normal function (not a static function) and I don't a reason that I shall declare int var
as static. Why does this happen.
Further, if I slightly modify the declaration of my method 'funPrivate(int arr[][var], int temp)' to this void funPrivate(int arr[][var])
then I get one more error:
error: 'arr' was not declared in this scope
Now, I don't know why does that happen. We pass the size of the array for our convenience, because there is no way to determine the size of the array in a function, but that shall not cause the error that arr was not declared in this scope
.
I have been thinking and searching a lot, but still can't find an answer. Please help. Thanks for any help in advance. :D
Upvotes: 0
Views: 194
Reputation: 206577
The member variable var
cannot be used in the declaration of an array like you are attempting in the function funPrivate
:
void funPrivate(int arr[][var], int temp)
Your best option is to use std::vector<std::vector<int>>
.
void funPrivate(std::vector<std::vector<int>> const& arr, int temp) {
cout << arr[0][0] << endl;
}
In the calling function, you can use:
void funPublic(){
std::vector<std::vector<int>> arr(var, std::vector<int>(var));
funPrivate(arr, var);
cout << "Hello";
};
Upvotes: 1