All pastes #505745 Raw Edit

Untitled

public cpp v1 · immutable
·published 2007-05-23 18:41 UTC
rendered paste body
//abstract Foo base classclass Foo {public:    virtual int getValue()=0;    virtual void setValue(int num)=0;};//specific implementation of Foo functionalityclass MyFoo : public Foo {private:    int* value;public:    Foo() {        value=new int;        *value=0;    }    ~Foo() {        delete value;    }    virtual int getValue() {        return *value;    }    virtual void setValue(int num) {        *value = num;    }};//anotherclass SimplerFoo : public Foo {private:    int value;public:    Foo() {        value=0;    }    //no destructor needed    virtual int getValue() {        return value;    }    virtual void setValue(int num) {        value = num;    }};//the following function can actually take a pointer to a MyFoo or a//SimplerFoo or any other class derived from Foo (even indirectly; like//one derived from MyFoo!)void setFourtyTwo(Foo* obj) {    //because it's declared as virtual, this will not call Foo::setValue    //(which in this case is pure virtual so it would even crash) but    //instead the setValue from the real class    obj->setValue(42);};int main() {    MyFoo one;    SimplerFoo two;    setFourtyTwo(&one);    setFourtyTwo(&two);};