All pastes #505759 Raw Edit

Untitled

public cpp v1 · immutable
·published 2007-05-23 18:53 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;    }};//abstract FooFactoryclass FooFactory {    virtual Foo* giveMeAFoo()=0;    virtual void deleteThisFoo(Foo* obj)=0;};//a factory to create those foo'sclass MyFooFactory : public FooFactory {    //methods have to have same name/return value/argument type than the    //class we're deriving from (ie FooFactory)    virtual Foo* giveMeAFoo() {        MyFoo* obj = new MyFoo();        //MyFoo is derived from Foo, so a MyFoo pointer can be        //converted to a Foo pointer directly        return obj;    }    virtual void deleteThisFoo(Foo* obj) {        //if MyFoo has a virtual destructor (which it should), this is        //actually calling MyFoo::~MyFoo(), not Foo's destructor (which is        //what we want, since ~Foo() wouldn't cleanup MyFoo-specific stuff).        delete obj;    }};//same comments apply on this oneclass SimplerFooFactory : public FooFactory {    virtual Foo* giveMeAFoo() {        SimplerFoo* obj = new SimplerFoo();        printf("And also log we're creating a SimplerFoo. Just because.\n");        return obj;    }    virtual void deleteThisFoo(Foo* obj) {        delete obj;    }};//Now see how the following code doesn't have to care a shit about how//the different kind of Foo's store their info, and setFourtyTwo doesn't//even know how they are created. And you can add more kinds of Foo's without//having to touch setAndGetValue or setFourtyTwo.//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);};void setAndGetValue(FooFactory* ff) {    Foo* obj;    obj = ff->giveMeAFoo();    setFourtyTwo(obj);    printf("%d\n",obj->getValue());    ff->deleteThisFoo(obj);}int main() {    MyFooFactory one;    SimplerFooFactory two;    setAndGetValue(&one);    setAndGetValue(&two);};