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?)
A pointer can also be initialized to null using any integer constant expression that evaluates to 0, for example char *a=0; . Such a pointer is a null pointer.
In C programming language a Null pointer is a pointer which is a variable with the value assigned as zero or having an address pointing to nothing. So we use keyword NULL to assign a variable to be a null pointer in C it is predefined macro.
A null pointer is a pointer which points nothing. Some uses of the null pointer are: a) To initialize a pointer variable when that pointer variable isn't assigned any valid memory address yet. b) To pass a null pointer to a function argument when we don't want to pass any valid memory address.
Initialization of C Pointer variablePointer Initialization is the process of assigning address of a variable to a pointer variable. Pointer variable can only contain address of a variable of the same data type. In C language address operator & is used to determine the address of a variable.
I wish to initialize
bar
toNULL
. 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.
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.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With