C++ Tips




Version 0.6
Copyright © 2009 by Zack Smith.
All rights reserved.

Introduction

This is just a page where I'm putting some minor details about C++.

The List

What are the expressions after a method declaration beginning with a colon for?

Foo () : a(5), b("foo")
{
   int a;
   std::str b;
}
They are the base initialization list. They can only be used with constructors. They are a convenient way to initialize variables before the code of the constructor is run. For instance, if you have a const value you can set it once and for all in the initialization list. It could be argued that initialization lists make C++ code more readable.

How does const work?

The const keyword is a source of much confusion for programmers. There are three basic things to remember:
  1. That const is sort of like a promise from a called function to the caller that it will not alter the constant data. The compiler enforces the promise.
  2. That a const pointer protects the pointed-to data whereas a const value protects the value itself.
  3. That the logic of const must be interpreted right-to-left.
  4. That a variable declaration can have more than one const keyword to identify the parts that will be constant. For example char const * const p; says that both the pointer and the pointed-to data are constant.

What is the commonly used "= 0" after a virtual function declaration?

This indicates that the class will not define the method function since it is a "pure virtual" method. Use it if you are creating an interface class i.e. one that defines an interface without providing any concrete code.

Do subclass destructors replace parent class destructors?

No. The subclass destructor is called, then the parent, then its parent if any. If a subclass pointer is changed to a parent class pointer however, only the parent class destructor will be called.

What is a virtual destructor for?

Imagine that you have for some reason converted the pointer of a derived-class object to a pointer of its parent class. Then you delete that object using that parent-class pointer. Normally only the parent-class destructor would be called; that's just how C++ works.

By making a parent class's destructor virtual, C++ is forced to call the proper derived-class destructors first.

class X {
public:
	X () { puts ("X constructor"); }
	virtual ~X () { puts ("X destructor"); }
};

class Y: X {
public:
	Y () { puts ("Y constructor"); }
	~Y () { puts ("Y destructor"); }
};

main()
{
	Y *b = new Y();
	X *a = (X*) b;
	delete a;
}
This will print:
X constructor
Y constructor
Y destructor
X destructor

Links





Valid HTML 4.01 Transitional