Search code examples
c++constructorinitializer-listcomma-operator

Why does the second variable not change in the field?


I'm testing some programms for my lectures. I'm creating classes and use a paramterlist to initalize a field but the second variable doesn't change.

#include <iostream>
using namespace std;

class Punkt {

    int x;
    int y;

public:
    Punkt(int a = 0, int b = 0)
    {
        x = a;
        y = b;

    }
    void printXY()
    {
        cout << "x= " << x << " y= " << y << endl;
    }
};

int main() {

    Punkt pFeld[] = { (1, 1), (2, 2), (3, 3) };

    for (int i = 0; i < 3; i++)
        pFeld[i].printXY();
    cin.get();
};

No error messages. Expected result was that x and y change, while actual result is that only x changes and y stays 0.


Solution

  • This

    (1, 1)
    

    is an expression with the comma operator.

    In fact this initialization

    Punkt pFeld[] = { (1, 1), (2, 2), (3, 3) };
    

    is equivalent to

    Punkt pFeld[] = { 1, 2, 3 };
    

    So the constructor with the second default argument equal to 0 is called three times.

    Use instead

    { 1, 1 }
    

    Here is your updated code

    #include <iostream>
    using namespace std;
    
    class Punkt {
    
        int x;
        int y;
    
    public:
        Punkt(int a = 0, int b = 0)
        {
            x = a;
            y = b;
    
        }
        void printXY()
        {
            cout << "x= " << x << " y= " << y << endl;
        }
    };
    
    int main() {
    
        Punkt pFeld[] = { {1, 1}, {2, 2}, {3, 3} };
    
        for (int i = 0; i < 3; i++)
            pFeld[i].printXY();
        cin.get();
    }
    

    Its output is

    x= 1 y= 1
    x= 2 y= 2
    x= 3 y= 3
    

    Pay attention to that the semicolon after the function main is redundant.