Asadullah Ansari

Build-Up Your Problem Solving Skill : Specially Using By C/C++/Data Structure Puzzles/New Technique Algorithm Design/ Understanding New Technology

Can You tell me All cases where Initialization list is mandatory in C++?

Posted by asadullahansari on August 20, 2008

Can you please tell me all possible cases where Constructor Initialization list is mandatory?

2 Responses to “Can You tell me All cases where Initialization list is mandatory in C++?”

  1. I know four cases where constructor Initialization list is mandatory.

    1. When data member of any class is constant then you have to use Initialization list .
    Example:
    class Test
    {
    public:
    const int aVar;
    Test();
    };
    Test::Test():aVar(SomeValue) //Initialization list

  2. 2. When data member of any class is reference variable then you have to use Initialization list .
    Example:

    class Test
    {
    public:
    int &aVar;
    Test();
    };
    Test::Test():aVar(liveObject) //Initialization list

    3. When Base class has no default constructor and you derived it then
    Initialization list is needed here.
    Example: i.e. Generalization

    class Base
    {
    int bCount;
    public:
    Base(int bVal);
    };
    class Derived: public Base
    {
    int dCount;
    public:
    Derived(int dVal);
    };

    Base::Base(int bVal)
    {
    bCount=bVal;
    }

    Derived::Derived(int dVal) : Base(dVal) //Iniatialization List Required
    {
    dCount=dVal;
    }

    4. When Your class has some data member which is object of any other class which has no default constructor,then on that case initialization list is required.

    Example: Association Relationship


    class Test
    {
    public:
    Test1 obj;
    Test(int j);
    } ;
    class Test1
    {
    public:
    Test1(int i);
    };
    Test::Test(int j):Test1(j) //Initialization List
    {
    }

    Please Give more and more comment on this. Add More Cases where Initialization List Is Mandatory.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: