ManticMoo.COM -> Jeff's Articles -> Programming Articles -> Initializing Member Vectors in a Constructor

How to initialize member vectors in a constructor

by Jeffrey P. Bigham

You've got a class and you've also got class, so you want to follow the advice of the C++ sages and initialize your data members in the constructor using the handy-dandy ":" constructor. This is straightforward in the normal case, just code like so:


class A
{
        int     a, b;
public:
        A() : a(234), b(120) { }
	void print() { cout << a << ":" << b << "\n"; }
};

This initializes values of a and b to 234 and 120, respectively, as you'd expect. And, in fact, it initializes them in that order and deinitializes them in the opposite order. That means if you instead were to initialize b(a) as so, then b would equal 234. Here's a trickier example along those lines where what happens is less clear but can probably be found in or is coming to a standard near you.

What if your member variables are pointers? It's very similar, although you'll want to initialize your member variables to a new instance created with new. You also have to be sure to delete these in the deconstructor. Some people argue against initializing pointers like this using the ":" constructor because it could be easier to overlook freeing that memory when you're done.

This example shows the basics of what you need to know:



class A
{
        int     a, b;
public:
        A() : a(234), b(120) { }
};

class B
{
        A* a_;
public:
        B() : a(new A()) { }
	~B() {delete a_;}
};

That's all you need to get started - happy coding!

ManticMoo.COM -> Jeff's Articles -> Programming Articles -> Initializing Member Vectors in a Constructor