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;
}

2 Responses to “Snippet: Pointer Usage: Polymorphism”

  1. on 24 May 2010 at 21:40:35 1.Anders Dalvander said …

    Snippet includes undefined behavior, class A should have a virtual destructor.

  2. on 25 May 2010 at 13:39:52 2.Tino Didriksen said …

    Indeed. Fixed.

Subscribe to the comments through RSS Feed

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image