Array declaration and allocation of memory inside class

Can I declare and allocate memory to an array in class as given below:
1
2
3
4
5
6
7
8
9
   class hci_test
 {  
    public:
    unsigned char* host_hci_pkt_arr;
    
    host_hci_pkt_arr = new(nothrow) unsigned char [2];
    host_hci_pkt_arr[0]  = 0x01;
    host_hci_pkt_arr[1]  = 0x02; 	                            
 };


While I am compiling above following errors are generated:

std::nothrow’ cannot appear in a constant-expression
hci_test.cpp:75: error: ‘new’ cannot appear in a constant-expression
hci_test.cpp:75: error: ISO C++ forbids declaration of ‘host_hci_pkt_arr’ with no type
hci_test.cpp:75: error: ISO C++ forbids initialization of member ‘host_hci_pkt_arr’
hci_test.cpp:75: error: making ‘host_hci_pkt_arr’ static
hci_test.cpp:75: error: ISO C++ forbids in-class initialization of non-const static member ‘host_hci_pkt_arr’
hci_test.cpp:75: error: declaration of ‘int hci_test::host_hci_pkt_arr’
hci_test.cpp:69: error: conflicts with previous declaration ‘unsigned char* hci_test::host_hci_pkt_arr’


Please tell me the solution.
In constructor, not class declaration.
processing code must be inside a function not a class, like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
   class hci_test
 {  
    public:
    unsigned char* host_hci_pkt_arr;

hci_test() // constructor
{    
    host_hci_pkt_arr = new(nothrow) unsigned char [2];
    host_hci_pkt_arr[0]  = 0x01;
    host_hci_pkt_arr[1]  = 0x02; 	                            
}
 };
thanks JockX and coder777, ya now its working.

in class there are two things data members and functions

and there is need of constructor if we want to initialize some variable or data member?
and there is need of constructor if we want to initialize some variable or data member?
yes
> and there is need of constructor if we want to initialize some variable or data member?

Yes.
The implementation can implicitly declare a constructor and synthesize it for us if we provide an initializer.

1
2
3
4
5
6
#include <new>

struct hci_test
{
    unsigned char* host_hci_pkt_arr = new (std::nothrow) unsigned char[2] { 1, 2 } ;
};


Why do you need new here? Why not

1
2
3
4
struct saner_hci_test
{
    unsigned char host_hci_pkt_arr[2] { 1, 2 } ;
};
Topic archived. No new replies allowed.