How to store user input in variable that is a different value than in the variable initialization in default constructor?

Sorry for the lengthy title of this post. However, I believe it sums up the issue I am having. I have a default constructor that sets these defaults every time an object gets called:
1
2
3
4
5
6
    Circles::Circles()
    {
       radius = 1;
       center_x = 0;
       center_y = 0;
    }

However, I want to give the user the option enter their own values. This would mean that the default values of radius, center_x and center_y must be ignored somehow. I set up the prompt like this:
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
    char enter;    // for user selection
    	float rad = 1; // for user selection
    	int x = 0, y = 0;     // for user selection
    
    	cout << "Would you like to enter a radius for sphere2? (Y/N): ";
    	cin.get(enter);
    
    	if (toupper(enter) != 'N')
    	{
    		cout << "Please enter a radius: ";
    		cin >> rad;
    	}
    
    	cout << endl;
    
    	cout << "Would you like to enter a center for sphere2? (Y/N): ";
    	cin.clear();
    	cin.ignore();
    	cin.get(enter);
    
    	if (toupper(enter) != 'N')
    	{
    		cout << "Please enter x: ";
    		cin >> x;
    		cout << "Please enter y: ";
    		cin >> y;
    	}
    
    	cout << endl << endl;
   
    	if (toupper(enter) == 'Y')
    		Circles sphere2(rad, x, y);
       Circles sphere2;


I want to pass rad, x, and y to this overloaded constructor:
1
2
3
4
5
6
Circles::Circles(float r, int x, int y)
{
   radius = r;
   center_x = x;
   center_y = y;
}


This is how the output gets sent to the screen:
1
2
3
4
cout << "Sphere2:\n";
cout << "The radius of the circle is " << radius << endl;
cout << "The center of the circle is (" << center_x 
     << "," << center_y << ")" << endl;

At last, we arrive at the problem that the default values get printed:

"The radius of the circle is 1 The center of the circle is (0,0)"

Why is this happening?
line 33 you redifine object sphere2 with default constructor
and sphere2 that defined before is destroyed after if ended
Line 32 is scoped to the if statement. It's the same as writing
1
2
3
4
5
// ↓ new scope starts here
if(toupper(enter) == 'Y')
{
	Circles sphere2(rad, x, y);
} // end scope 

sphere2 is defined inside this scope, so it doesn't exist outside of it. For this reason line 33 is not giving you an error: redefining a variable is illegal, but since the first sphere2 doesn't exist here you can create a different object named sphere2.
Last edited on
Topic archived. No new replies allowed.