Ashish
Ashish

Reputation: 43

Initialize member variables with multiple constructor calls

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?

Upvotes: 2

Views: 374

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

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;
    }
};

Upvotes: 3

xinaiz
xinaiz

Reputation: 7788

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;
   }
};

Upvotes: 1

Related Questions