I have an array of struct having const variables; I am initialize by using constructor initializer list, but if I make an array of that struct how to initialise all the elements of array of that structure. if the struct contains no const var, then it is easily done
if the struct contains no const var, then it is easily done
#include<iostream>
struct s_Nconst{
int num;
int x1;
// s_Nconst(int);
};
int main(){
s_Nconst sN2;
sN2.num=5;
std::cout<<"initial values of num\t"<<sN2.num<<std::endl;
//making array of s_Nconst struct
s_Nconst sN3[sN2.num];
for(int i=sN2.num-1; i>-1; i--,++sN2.num){
sN3[i].x1= sN2.num;
std::cout<<"sn3["<<i+1<<"]\t"<<sN3[i].x1<<std::endl;
}
return 0;
}
but if suppose the struct comprises of const var, then I am able to make single object of the struct using the constructor initializer list, but if I am going to make array of the struct it is giving error
#include<iostream>
struct s_const{
const int x1,y1,z1;
static int num;
s_const(int,int,int);
};
s_const::s_const(int x,int y, int z)
:x1(x),y1(y),z1(z) {
std::cout<<"initial values of x1,y1,z1\t"<<this->x1<<" "<<this->y1<<" "<<this->z1<<std::endl;
}
/*struct s_Nconst{
int num;
int x1;
// s_Nconst(int);
};
s_Nconst::s_Nconst(int x)
:num(x){
std::cout<<"initial values of num\t"<<this->num<<std::endl;
} */
int main(){
int a,b,c;
a=1;b=2;c=3;
s_const s1(a,b,c);
//array of s1 is giving error
s_const sc[3];
//s_Nconst s2(++c);
//s_Nconst sN2;
//sN2.num=5;
//std::cout<<"initial values of num\t"<<sN2.num<<std::endl;
//making array of s_Nconst struct
//s_Nconst sN3[sN2.num];
//for(int i=sN2.num-1; i>-1; i--,++sN2.num){
// sN3[i].x1= sN2.num;
std::cout<<"sn3["<<i+1<<"]\t"<<sN3[i].x1<<std::endl;
//}
return 0;
}
is there any way to make array of structs having const variables and how to initialize them?
sN3[i].x1= sN2.num;like you are doing in non-constexample, isn't initialization. It's assignment.s_const sc[3] = {s_const (1, 2, 3), s_const (4, 5, 6), s_const (7, 8, 9)};would be initialization.s_const sc[3]{ {1,1,1}, {1,1,1}, {1,1,1} };.s_Nconst sN3[sN2.num];is invalid and use VLA extension, preferstd::vector.constmembers. "Whatever value they have when you declare them is the value they will have for the entire execution." - not trueconst-qualified ones.