Saturday, January 30, 2016

C++11 and initializer list

This post is about one example of using initializer list in C++.

Imagine a parent child relationship between two classes.
Parent has a child (obviously).
Child has a pointer back to the parent.
Now the Child is not a pointer in the parent class, but a member object.

Here a simple and easy way to use initializer list in order to pass parents' "this" pointer to the constructor of the Child class

Class Child
{
private:
Parent* p;

public:
Child(Parent* p1): p(p1){}
};


Class Parent
{
private:
Child c;

public:
Parent(): c(this){}
};

This is perfectly fine. One can use "this" pointer inside the initalizer list or constructor as long as the object to which "this" pointer has been passed on to (i.e the child object), does not use the uninitialized members or virtual functions of the parent class.

For e.g Child class's constructor should not use any uninitialized pointers or members of parent class. Child class' constructor should not call any virtual function as well because one might expect the child class's virtual function definition to  be invoked. But it would in fact invoke the parent class's virtual function definition if any because the child class's virtual function will not be visible inside the child class's constructor.

Hence, uninitialized members are not yet initialized, and virtual functions would result in calling the base class function instead of derived class function.

No comments: