RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Sequence Constructors Add C++09 Initialization Syntax to Your Homemade Classes

You can initialize C++09 Standard Library containers with a list of initializers, but what about your homemade container classes? Sequence constructors enable you to initialize instances of your homemade classes in a similar fashion.

previous 10-Minute Solution demonstrated the new initialization rules of C++09, which enable you to initialize standard containers (among the rest) in the following manner:

vector <int> scores = {89, 76, 98, 93}; //C++09

A new constructor type called a sequence constructor makes this syntax possible. The following sections will show how to enable the ={val1,val2,...} initialization syntax by adding a sequence constructor to your homemade classes.

Unlike C++09 Standard Library containers, your homemade container classes don't support the new initializer list syntax.

Adding a sequence constructor to your homemade container classes will allow you to initialize instances of those classes similarly to the new initializers in the C++09 Standard Library containers.

I Want C++09 Containers' Easy Initialization

Suppose you designed a polymorphic container class with certain operations that C++09 standard container classes don't support. In all other aspects, however, your homemade container has the same interface as a standard container:

template <typename T> class MyVector
 T* elements;
 size_t n;
 virtual void reserve(size_t n); //polymorphic
 T& operator[] (int idx);
 size_t size() const;

Here's the snag. Unlike with standard C++09 container classes, populating a MyVector object in your homemade container is an arduous task. You first need to default-construct MyVector and then call push_back() or assign(). The following code demonstrates the difference between standard C++09 containers and homemade containers:

//easy initialization of a standard C++09 container  
std::vector <int> vi={5,6,7,8}; 

//alas, "initializing" MyVector is tedious and bug prone
int arr[]={0,2,4,8}; 
MyVector <int> vi;  
vi.assign(arr, arr+4);

Now suppose you want MyVector to support the same convenient initialization syntax that C++09 containers provide. What is the secret ingredient that C++09 containers use to enable such easy initialization? Answer: Sequence constructors.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date