Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
void walk(class Base *bar [], int count) {
	for (int i = 0; i < count; i++) {
		(bar[i])->func();
	}
}

int main(void) {
	Base* dis[3] = {new Base, new Base, new Base};
	Base* dat[3] = {new Derived, new Derived, new Derived};

	walk(dis, 3);
	walk(dat, 3);

  for (int i = 0; i < 3; i++) {
    delete dis[i];
    delete dat[i];
  }
}

The elements in the arrays are now all the same size (because they are pointers to Base or Derived objects) and there is no problem with the array indexing.

...

Code Block
bgColor#ccccff
void walk(vector<Base*>bar) {
	for_each (bar.begin(), bar.end(), mem_fun(&Base::func));
}

int main(void) {
	vector<Base*> dis(3);
        for (int i=0; i<3; i++) dis[i] = new Base;

	vector<Base*> dat(3);
        for (int i=0; i<3; i++) dat[i] = new Derived;

	walk(dis);
	walk(dat);

  for (int i = 0; i < 3; i++) {
    delete dis[i];
    delete dat[i];
  }
}

Risk Assessment

Using arrays polymorphically can result in memory corruption, which could lead to an attacker being able to execute arbitrary code.

...