C++ Polymorphism

From Schmid.wiki
Jump to: navigation, search

Contents

Virtual Functions

Behaviour

If we assume the following definitions (remember that a struct is defined as a class with default public: access):

struct Base {                             
    Base() : x(4) {}                      
    virtual int getValue() { return x; }  
    int x;                                
};                                        
struct Derived : public Base {            
    int getValue() { return  2 * x; }     
};                                        
...
Base b;
Derived d;                            
Base *dp = &d; // pointer (upcasted)
Base &dr = d;  // reference (upcasted)
                                      

We get the following behaviour:

b.getValue();   // not pointer or reference, selects Base::getValue
d.getValue();   // not pointer or reference, selects Derived::getValue
dp->getValue(); // virtual member function, selects Derived::getValue
dr.getValue();  // virtual member function, selects Derived::getValue

- See C++ Virtual Functions Disassembled for more information.

References

Downcasting

Use dynamic_cast<> to downcast from a polymorphic base class object to an inherited object. A polymorphic class is one with a virtual method. If it doesn't have one in the design, use the virtual destructor hack:

class Something {
    virtual ~Something() {}; ///< Force polymorphism
};

Abstract Base Classes / Interfaces

An abstract base class (or interface) in C++ is one that has a pure virtual method.

class Foo {
public:
    virtual void doStuff() = 0; // this one is pure virtual,
                                // so Foo is abstract
};
Personal tools