0
Help understand this code it's just outputs 2 thing's ot error
#include <iostream> #include <string> using namespace std; class point { public: int *data; point(int size) { this->data=new int[size]; for(int i=0;i<10;i++) < what's happening here is { is it changing anything what's making "for" here? data[i]=i; } cout<<"constructor"<<endl; } ~point() { delete[] data; cout<<"destructor"<<endl; } void print(int size) { cout<<"func"<<*data<<this<<endl; } point foo() { point temp(1); return temp; } }; int main() { point add(1); return 0; } https://code.sololearn.com/cP3ooW12leL6/?ref=app
8 Answers
0
You allocate <size> amount of `int` block for <data>, then you try to fill 10 blocks using a for-loop in the class constructor.
But notice this, in main function you instantiate `point` class with just 1 -> `point add(1)`. Yet again, the for-loop in constructor tries to fill up to 10 blocks. Idk, but that didn't look right to me, somehow : )
+ 1
Thanks
0
Thanks but I know that function for bro , I'm asking how can I use it (for) in this code : )
0
Can you make some example? : )
0
I was thinking just replace the 10 in the for-loop with <size>, that way you won't be using more than what was allocated for <data>.
for(int i = 0; i < size; i++)
When you create an instance in main function, you pass 1 as constructor argument, so the constructor reserve 1 block of `int` for you. But the for-loop in constructor tries to use more (up to 10 blocks), because the for-loop condition specifies `i < 10` : )
0
(My English is not so good )
What this code need to output if I'll use all 10 blocks : )
0
Change the print function as follows:
void print(int size)
{
for(int i = 0; i < size; i++)
{
cout << data[i] << endl;
}
}
And call it in main ...
add.print(10)
That's it I guess ...