2

I'm trying to execute the following code:

 #include <iostream>
using namespace std;

class ABC {
private:
    int x, y;
public:
    ABC(){
        cout << "Default constructor called!" << endl;
        ABC(2, 3);
        cout << x << " " << y << endl;
    }
    ABC(int i, int j){
        cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << endl;
        x = i;
        y = j;
        cout << x << " " << y << endl;
    }
};

int main(){
    ABC a;
    return 0;
}

I am getting the following output:

Default constructor called!
Parameterized constructor called with parameters 2 3!
2 3
-858993460 -858993460

Shouldn't the member variables be initialized with values 2 and 3?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Ashish
  • 43
  • 5

2 Answers2

3

ABC(2, 3); doesn't call the constructor to initialize the members, it just create a temporary variable which will be destroyed immediately.

If you meant delegating constructor you should:

ABC() : ABC(2, 3) {
    cout << "Default constructor called!" << endl;
    cout << x << " " << y << endl;
}

Note this is a C++11 feature. You can add a member function if you can't use C++11.

class ABC {
private:
    int x, y;
    init(int i, int j) {
        x = i;
        y = j;
    }
public:
    ABC(){
        cout << "Default constructor called!" << endl;
        init(2, 3);
        cout << x << " " << y << endl;
    }
    ABC(int i, int j){
        cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << endl;
        init(i, j);
        cout << x << " " << y << endl;
    }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

You create a temporary variable in ABC() body. You can use this syntax to overcome this:

class ABC 
{
private:
   int x, y;
public:
   ABC() : ABC(2,3)
   {
       std::cout << "Default constructor called!" << std::endl;
   }
   ABC(int i, int j)
   {
       std::cout << "Parameterized constructor called with parameters "<< i << " " << j << "!" << std::endl;
       x = i;
       y = j;
       std::cout << x << " " << y << std::endl;
   }
};
xinaiz
  • 7,744
  • 6
  • 34
  • 78
  • I can't compile this block of code on the IDE I'm using (Visual Studio 2010 Professional). > Error 1 error C2614: 'ABC' : illegal member initialization: 'ABC' is not a base or member – Ashish Jul 19 '16 at 06:35
  • 1
    @Ashish This is available with the current c++11 standard only. VS2010 is too old. – πάντα ῥεῖ Jul 19 '16 at 06:35