Asif Mushtaq
Asif Mushtaq

Reputation: 3798

Any Example that Prove Initializer List Call before Constructor C++

I have searched but still didn't get easy and proper answer, Below is my code.

#include <iostream>
using namespace std;

class Parent
{
    private:
        int a;

    public:
        Parent():a(3) { cout << a; }
};

int main()
{
    Parent obj; 
    return 0;
}

Can you add additional lines of code that can prove or show me that initializer list call before constructor?

Upvotes: 0

Views: 55

Answers (4)

Venkata Naidu M
Venkata Naidu M

Reputation: 351

You don't get variable "a" value 10 in this program , a assigned before constructor method called .

 #include<iostream>
using namespace std;
class Test
{
    public:
        int a,b;
    public:
        Test():a(b){
            b=10;
        }
};

int main()
{
   Test obj;
   cout<<"a :"<<obj.a<<" b:"<<obj.b;
   return 0;
}

Upvotes: 1

Avi Ginsburg
Avi Ginsburg

Reputation: 10596

I would modify you code ever so slightly:

#include <iostream>
using namespace std;
class Parent
{
    public:
        int a;
    public:
        Parent():a(3){
            a = 4;
        }

};

int main()
{
    Parent obj;
    cout << obj.a;

    return 0;
}

The output is 4, thus a was initialized with 3 and then assigned 4.

Upvotes: 3

hyde
hyde

Reputation: 62878

Simply add data member, which has constructor, which prints something. Example:

#include <iostream>
using namespace std;

struct Data {
    Data(int a) { 
        cout << "Data constructor with a=" << a << endl;
    }
};

class Parent
{
    private:
        Data a;
    public:
        Parent():a(3){
            cout << "Parent constructor" << endl;
        }
};

int main()
{
   Parent obj;
   return 0;
}

Output:

Data constructor with a=3
Parent constructor

Conclusion: Data constructor was called before constructor body of Parent.

Upvotes: 1

Levi
Levi

Reputation: 1983

This is best shown with multiple classes:

#include <iostream>

class A
{
    public:
        A()
        {
             std::cout << "Hello World!" << std::endl;
        }
};

class B
{
    private:
        A* a;

    public:
        // Call a's constructor
        B():a(new A)
        {
             // Some code
        }

        ~B()
        {
            delete a;
        }
};

int main()
{
    B obj;
    return 0;
}

Upvotes: 0

Related Questions