From Schmid.wiki
Jump to: navigation, search

inline Methods

class Thing {
public:
    void hello(void) { cout << "hello"; } // this is inline
    void goodbye(void);
};
inline void Thing::goodbye(void) {   // this is also inline
    cout << "goodbye";
}

Virtual Destructor

#include <iostream>
struct Base {
    virtual ~Base() { std::cout << "base dtor\n"; }
};
class Derived : public Base {
    ~Derived()      { std::cout << "derived dtor\n"; }
};
int main(void) {
    Derived *d = new Derived();
    Base    *b = d;
    delete b;
}

Output:

derived dtor
base dtor

In this example, if Base::~Base() wasn't virtual, Derived::~Derived() wouldn't be called. To ensure that derived classes are properly destructed, you must define a virtual Base class destructor!

Returning a New Object

Thing* getThing(void) { return new Thing; }
Thing myThing* = getThing();
delete myThing;              // deallocate when not needed anymore

Get instance of class itself:

class Foo {
public:
    static Foo getInstance();
};
static Foo Foo::getInstance() {
    return new Foo();
}
Foo myFoo = Foo::getInstance();