Search code examples
c++constructorgarbage

Calling Constructor with in constructor in same class


I was expecting the output 2, 3 but I'm getting garbage value. Why's that?

Here's my code:

#include <iostream>
using namespace std;

class A
{
public:
    int a, b;

    A()
    {
        cout << a << " " << b;
    }

    A(int x, int y)
    {
        a = x;
        b = y;
        A(); // calling the default constructor
    }
};

int main()
{
    A ob(2, 3);
    return 0;
}

Solution

  • Inside this constructor:

    A(int x, int y)
    {
        a = x;
        b = y;
        A(); // calling the default constructor
    }
    

    call A(); creates a new temporary object that is immediately deleted after this statement. Because the default constructor A() does not initializes data members a and b then it outputs a garbage.

    This temporary object has nothing common with the object created by constructor A( int, int ).

    You could rewrite your class the following way:

    class A
    {
    public:
        int a, b;
    
        A(): A(0, 0) {}
    
        A(int x, int y) : a(x), b(y)
        {
            cout << a << " " << b;
        }
    };