Home > Software design >  Getting an unusual output for a simple constructor program in C
Getting an unusual output for a simple constructor program in C

Time:12-17

I am a novice at C and have encountered an unusual error while trying to learn about constructors. Here I am trying to make x = 5 and y = 6, then have the program print them out to the screen.

This is my program ->

#include <iostream>
using namespace std;

class class1 {
    public:
        int x;
        int y;
        class1(int x, int y) {
            x = x;
            y = y;
        }
}




int main() {
class1 class1obj(5, 6);
cout << class1obj.x << endl << class1obj.y;

}

This is my output after 3 runs ->

1st run

172691493
1

2nd run

126890021
1

3rd run

226783269
1

As you can see from the outputs, y seems to be a constant '1' whereas x just seems to change continuously through random numbers. This program is fairly simple so I have not a clue on what is going wrong here.

It should also be noted that I am on a mac OS big sur and I use g -std=c 11 as my compiler as g does not seem to work for all my programs (and yes I have tried g on its own for this specific program and it still does not work).

Any help will be much Appreciated!

CodePudding user response:

This :

   class1(int x, int y) {
        x = x;
        y = y;
    }

is called shadowing. A variable shadows another one of same name. x = x just assigns the value of the parameter x to itself and the members are left uninitialized. The compiler has no way to know that you want one x to be the member and the other be the parameter, instead the parameter is said to "shadow" the member and in x = x; the x is the parameter. You should use different names:

   class1(int a, int b) {
        x = a;
        y = b;
    }

or use the member initializer list (which you should prefer anyhow):

   class1(int a, int b) : x(a),y(b) {}

There is no ambiguity in the initializer list about what x refers to:

   class1(int x, int y) : x(x),y(y) {}

In x(x) the first x can only refer to the member and the second x can only refer to the argument.

  • Related