Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot (jp)

...

Code Block
bgColor#FFCCCC
class Base {
public:
	virtual void func(void) {
		cout << "Base" <<&lt;&lt; &quot;Base&quot; &lt;&lt; endl;
	}
};

class Derived : public Base {
public:
	int i;
	Derived() { i = 0; }

	void func(void) {
		cout << "Derived " <<&lt;&lt; &quot;Derived &quot; &lt;&lt; ++i <<&lt;&lt; endl;
	}
};

void walk(class Base *bar, int count) {
	for (int i = 0; i <&lt; count; i++) {
		bar[i].func();
	}
}

int main(void) {
	Base dis[3];
	Derived dat[3];

	walk(dis, 3);
	walk(dat, 3); // crashes
}

...

Code Block
bgColor#ccccff
void walk(class Base *bar [], int count) {
	for (int i = 0; i <&lt; count; i++) {
		(bar[i])->func&gt;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);
}

...

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

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

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

	walk(dis);
	walk(dat);
}

...

Wiki Markup
\[[Stroustrup 06|AA. C++ References#Stroustrup 06]\] What's wrong with arrays?

...

OBJ30-C. Do not use pointer arithmetic polymorphically      13. Object Orientation (OBJ)      OBJ33-C. Do not slice polymorphic objects