Following the first answer to this question, I ran into an issue with overriding variables. This is the code I wrote to find the root of the problem:
#include <iostream>
using namespace std;
class foo
{
private:
int *bar;
int l;
public:
foo(int bar);
~foo();
void print_bar() {
cout << "bar = {"; for (int i = 0; i < l; i++) {cout << + bar[i] << ", ";} cout << "}" << endl;
}
};
foo::foo(int l) {
this->l = l;
cout << "Creating with length " << l << endl;
bar = new int[l];
cout << "{"; for (int i = 0; i < l; i++) {cout << + bar[i] << ", ";} cout << "}" << endl;
for(size_t i = 0; i < l; ++i) {bar[i] = 0;}
cout << "Created with bar = {"; for (int i = 0; i < l; i++) {cout << + bar[i] << ", ";} cout << "}" << endl;
}
foo::~foo() {
cout << "Deleted with bar = {"; for (int i = 0; i < l; i++) {cout << + bar[i] << ", ";} cout << "}" << endl;
delete[] bar;
}
int main() {
foo a = foo(1);
a = foo(2);
a.print_bar();
return 0;
}
This outputs:
Creating with length 1
{0, }
Created with bar = {0, }
Creating with length 2
{0, 0, }
Created with bar = {0, 0, }
Deleted with bar = {0, 0, }
bar = {1431655787, 5, }
Deleted with bar = {1431655787, 5, }
Instead of what I expected:
Creating with length 1
{0, }
Created with bar = {0, }
Creating with length 2
{0, 0, }
Created with bar = {0, 0, }
Deleted with bar = {0, }
bar = {0, 0, }
Deleted with bar = {0, 0, }
How can I avoid this, or is there a better way to have a class with a variable length array as a parameter?
(Please keep in mind when answering that I'm very new to c++.)