why I am getting this
request for member set in b which is of non class type box[5]
please provide solution its urgent
I am calculating volume of box and storing length breadth and volume in box array of objects
what can I do to solve this?
#include<iostream>
using namespace std;
class box
{
int length;
int breadth;
int height;
int n;
int volume;
box *b;
public:
box()
{
}
void set(int n)
{
for(int i=0;i<n;i++)
{this->b=new box[5];
int len,bre,hei,vol;
cout<<"enter length"<<endl;
cin>>len;
cout<<"enter breadth"<<endl;
cin>>bre;
cout<<"enter height"<<endl;
cin>>hei;
cout<<"enter volume"<<endl;
cin>>vol;
b[i].length=len;
b[i].breadth=bre;
b[i].height=hei;
b[i].volume=vol;
}
}
void get()
{
for(int i=0;i<n;i++)
{
cout<<"length "<<b[i].length;
cout<<"breadth "<<b[i].breadth;
cout<<"height "<<b[i].height;
cout<<"volume "<<b[i].volume;
}
}
};
int main()
{
box b[5];
b.set(5);
b.get();
}
>Solution :
emphasized textThe variable b declared in main
box b[5];
has an array type. Arrays do not have member functions. So this statement
b.set(5);
is incorrect. You could write for example
b[0].set( 5 );
However within the member function set there is used uninitialized pointer b
b[i].length=len;
b[i].breadth=bre;
b[i].height=hei;
b[i].volume=vol;
that invokes undefined behavior.
So your code as is just does not make a sense.
It seems you need a static member function like for example
static void set(box b[], int n)
{
for(int i=0;i<n;i++)
{
int len,bre,hei,vol;
cout<<"enter length"<<endl;
cin>>len;
cout<<"enter breadth"<<endl;
cin>>bre;
cout<<"enter height"<<endl;
cin>>hei;
cout<<"enter volume"<<endl;
cin>>vol;
b[i].length=len;
b[i].breadth=bre;
b[i].height=hei;
b[i].volume=vol;
}
}
And call it like
box b[5];
box::set( b, 5 );
In this case you should remove the data members b and n
int n;
box *b;
in the class definition.
The function get can be declared and defined the following way
void get() const
{
cout<<"length "<< length << '\n';
cout<<"breadth "<< breadth << '\n';
cout<<"height "<< height << '\n';
cout<<"volume "<< volume << '\n';
}
And for the declared array in main the function can be called the following way
for ( const auto &item : b )
{
item.get();
cout << '\n';
}