C++ 31 Jan 2010 23:23:58
Snippet: Pointer Usage: Polymorphism
//tinodidriksen.com/uploads/code/cpp/pointer-polymorphism.cpp
#include <iostream>
struct A {
virtual void foo() {
std::cout << "A::foo()" << std::endl;
}
virtual ~A() {
}
};
struct B : public A {
void foo() {
std::cout << "B::foo()" << std::endl;
}
};
int main() {
A *a = new A;
a->foo();
delete a;
a = new B;
a->foo();
delete a;
}

on 24 May 2010 at 21:40:35 1.Anders Dalvander said …
Snippet includes undefined behavior, class A should have a virtual destructor.
on 25 May 2010 at 13:39:52 2.Tino Didriksen said …
Indeed. Fixed.