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;
}
                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;
    }
};
                        You didn't call the default constructor, what you did is create a temporary A object, which happen to have its members uninitialized before you printed the output. Perhaps what you wanted to do is constructor delegation, which would look like
#include <iostream>
class A
{
    int a, b;
public:
    A(): A( 0, 0 ) {
        std::cout << a << ", " << b << std::endl;
    }
    A( int x, int y ): a( x ), b( y ) {}
}
int main()
{
    A object_a {}; //prints 0, 0
    return 0;
}
                        Here you output a and b which are not initialized:
A(){
cout<<a<<" "<<b;
}
And here you initialize a and b, but you create an anonlymous temporary object
A(int x , int y){
    a = x; b= y;
    A(); // !!!! CREATES AT TEMPORARY ANONYMOUS OBJECT WITH IT'S OWN a and B
}
To use a delegated constructor (i.e. using another constructor to finish the construction process of the SAME object) you have to use the delegeted constructor in the initialisation list :
A(int x , int y) : A() { a=x; b=y;  } 
Unfortunately, when you use delegation, the delegate must be the ONLY meminitializer in the list. This requires that the initialisation of a and b would happen after A().
Another alternative:
class A
{
public:
    int a, b;
    A() :  A(0, 0) { }  // use a delegated ctor 
    A(int x, int y) : a(x), b(y) { cout << a << " " << b; }
};
Still another alternative, using defaults (without reusing a constructor) :
class A
{
public:
    int a, b;
    A(int x=0, int y=0) : a(x), b(y) { cout << a << " " << b; }
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With