C++: Initialize a member pointer to null?

Nick Heiner picture Nick Heiner · Jul 7, 2010 · Viewed 31.3k times · Source

I have a class that looks like:

class Foo
{
public:
    Foo();
    virtual ~Foo();

private:
    Odp* bar;
};

I wish to initialize bar to NULL. Is this the best way to do it?

Foo::Foo() : bar(NULL)
{
}

Also, is it necessary that the destructor is virtual? (If that is true, then must the constructor be virtual as well?)

Answer

greyfade picture greyfade · Jul 7, 2010

I wish to initialize bar to NULL. Is this the best way to do it?

It is the correct way. So, yes.

Also, is it necessary that the destructor is virtual?

No. The destructor only needs to be virtual if you will be inheriting from the Foo class and will be using a Foo pointer to delete those derived classes (although as a general rule of thumb, it should be virtual if there are any other virtual members).

(If that is true, then must the constructor be virtual as well?)

No. Constructors neither need to be virtual, nor can they.