Class
according to me the output of the following program should be 2 and 4 but its not,y?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include<iostream>
using namespace std;
class Bix
{
int x, y;
public:
void show(void);
void main(void);
};
void Bix::show(void)
{
Bix b;
b.x = 2;
b.y = 4;
cout<< x << " " << y;
}
void Bix::main(void)
{
Bix b;
b.x = 6;
b.y = 8;
b.show();
}
int main()
{
Bix run;
run.main();
return 0;
}
|
Last edited on
Line 16 is printing out x and y of the object the show function was called on, not the b object that is created new in show.
Changing line 16 to cout<< b.x << " " << b.y;
would give the result you think you should be getting (I assume you mean 2 and 4 instead of 2 and 3?).
Why are Bix::main and Bix::show creating private instances of Bix named b?
When you call a member function, you implicitly have access to the instance's member variables.
Line 28: Calls the main function of instance run. run's x and y variables are uninitialized.
Lines 20-22: Creates a new Bix instance called b and sets b's x and y to 6 and 8.
Line 23: Calls b's show function.
Lines 13-15: Creates a new private copy of Bix named b. Unrelated to the current instance. Sets local instance x and y to 2 and 4 respectively.
Line 16: Displays the x and y values from the caller's instance (line 20). You should be seeing 6 and 8 displayed.
I don't have a clue why you're doing it this way. Conventional coding would be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include<iostream>
using namespace std;
class Bix
{ int x, y;
public:
Bix ();
Bix (int ix, int iy);
void show();
};
// Default constructor assigns default values to x & y
Bix::Bix ()
{ x = 0;
y = 0;
}
// Explicit constructor assigns initial values
Bix::Bix (int ix, int iy)
{ x = ix;
y = iy;
}
void Bix::show()
{ cout<< x << " " << y;
}
int main()
{ Bix run (2,3);
run.show();
return 0;
}
|
Topic archived. No new replies allowed.