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?)
Virtual functions are to determine which function of class (which is defined in both base and derived class) must be called during run time. But when object is created compiler knows which constructor is to be called. for eg. when base object is created base constructor is calledand same for the derived class. Hence making constructor to be virtual doesnt makes any sense.But once when the base class object pointer points to the derived class object, and then destructor is called ,compiler gets confused which destructor(either of baseor derived) needs to be called, which is can only resolved using lookup table vtable and hence destructor needs to be virtual.
It is the correct way. So, yes.
No. The destructor only needs to be virtual if you will be inheriting from the
Foo
class and will be using aFoo
pointer to delete those derived classes (although as a general rule of thumb, it should be virtual if there are any other virtual members).No. Constructors neither need to be
virtual
, nor can they.Four distinct ways exist. Which one is the best is up to you
1, yes
2, only if you want somebody to be able to derive from your class and use a pointer to the base class - but make the dtor virtual anyway
3, no you can't have a virtual ctor (or all ctors are virtual I suppose?)
Yes, the initializer list is best.
Maybe. The destructor should be virtual if you intend to have any other virtual functions in the class, or if you intend the class to be inherited from (although usually those things go together).
No. It's not possible to have a virtual constructor in C++. (what would such a thing even mean?)
The nature of your question suggests to me that you don't really understand what the
virtual
keyword does, or what is is for, and you are just copying something you saw elsewhere or in a tutorial. It's best to understand the purpose of all of the code you're writing. Here might be a place to start: http://www.parashift.com/c++-faq-lite/virtual-functions.htmlAnother option you might want to consider is to use a smart pointer class (such as
boost::scoped_ptr
,boost::shared_ptr
or C++0x'sunique_ptr
) instead of a raw pointer. The constructor of the smart pointer will make sure it's initialized to something NULL-like if you don't need some other explicit initialization. The smart pointer will also ensure that the pointed-to object is destroyed.You just need to decide what kind of smart point policy is appropriate for the item and choose accordingly (even
auto_ptr
might be better than a raw pointer as long as you're aware of the various pitfalls).