hi guys i want to achieve something like this :
in header file :

#pragma once

class wef
{
private:
	int a[];
	void setI();
};

and the code file will be like this:

#include "wef.h"

 
void wef::setI()
{
	a = {1,2,3};
}

could you please help me with that?

Recommended Answers

All 5 Replies

You can't do it; the size of the array needs to be specified in the class declaration. If you want something variable-sized, use a vector.

You should change the array definition to this:
int a[3];
...and the allocation to this:
a[0] = 1
a[1] = 2
a[2] = 3

If you require dynamically sized arrays you should read into dynamic memory allocation with C++.

Regards,
Adam

Edit: or use a std::vector

ok i found out how to do that:

test.h :

class test
{
    public:
  static const int myArray[];

};

test.cpp :

#include "test.h"
#include <iostream>
using namespace std;
const int  test::myArray[]={1,2,3,4,5};

int main()
{

for(int i=0;i<5;i++)
{
  cout << test::myArray[i] << endl;
}

}

When i run the code the output is :
1
2
3
4
5

I also suspected if it is mystery of keyword static or const then i also created the same thing without const keyword.

test.h :

class test
{
    public:
  static  int myArray[];

};

test.cpp :

#include "test.h"
#include <iostream>
using namespace std;
 int  test::myArray[]={1,2,3,4,5};

int main()
{

for(int i=0;i<5;i++)
{
  cout << test::myArray[i] << endl;
}

}

the output is the same as the previous :
1
2
3
4
5

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.