How to send value to multiple constructors at object definition?

I have a simple program that determines the radius, area, and circumference of a circle. I want to have three constructors: the default constructor should sets the default values, the first overloaded constructor sets a value for radius, and the second overloaded constructor sets a value for the center of the circle.

However, at definition I would like to define a circle's radius AND its center by calling its constructors. When I try to do something like this:

1
2
Circles sphere(8);
Circles sphere(9,10);


I get a compiler error that makes sense: "error: redefinition of 'sphere'".

So how can I define attributes using two different constructors at object definition?

Here is my code (many functions left out as they are not relevant:

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
34
35
36
37
38
39
40
41
class Circles    
{
	public:
   		Circles (float r);       // Constructor
   		Circles();               // Default constructor
        Circles (int, int);              // Constructor for setting the center
	private: 
   		float  radius;
   		int    center_x;
   		int    center_y;
};      

int main()
{
   Circles sphere(8);
   Circles sphere(9,10);

   //...
}

//Implementation section     Member function implementation

Circles::Circles()
{
   radius = 1;
   center_x = 0;
   center_y = 0;
}

Circles::Circles(float r)
{
   radius = r;
}

// Constructor for setting center 
Circles::Circles(int x, int y)
{
   center_x = x;
   center_y = y;
}


Thanks!
In main you have to match the number of arguments in the constructor to main. if you say Circles(int, int) then you need to provide the arguments in main.
1
2
3
4
5
6
7
8
class Circle
{
private:
	int radius;
public:
	Circle(int x, int y){}

};


I am not sure how you are accessing the elements. I need a main and the class to compare.
cheers!
I dont know if its possibe or not
Maybe add another constructor ?
or add setter function for radius ?
I would add another class that defines the shape.

then a function in the circle class that draw() the shape.

hmm, where is the trouble exactly.

give me a main() example of how you are accessing the class.

The class and main are very connected.
Last edited on
1
2
    Circles sphere(8);
    Circles sphere(9,10);
These lines define two separate objects with the same name (illegal).
If you want to set all the members from a single constructor call, write one that takes all the parameters needed to set them,
public Circles(float r, int x, int y);

Data doesn't have to be set from the ctor. void Circles::SetCenter(int x, int y)... is perfectly fine.
Topic archived. No new replies allowed.