#include <iostream>
using namespace std;
class Circle{
private:
float radius;
float xCoord;
float yCoord;
public:
Circle():radius(0),xCoord(0),yCoord(0){};
Circle(float r, float x, float y): radius(r), xCoord(x),yCoord(y){};
void PrintCircle(){
cout << radius << ' ' << xCoord << ' ' << yCoord;
}
};
class Cylinder{
private:
Circle circle;
float height;
public:
Cylinder():height(0){};
Cylinder(float r, float x, float y, float h):circle(r,x,y),height(h){};
void PrintCylinder(){
circle.PrintCircle();
cout << ' ' << height << endl;
}
};
int main(){
Cylinder c1;
c1.PrintCylinder();
Cylinder c2(5,5,5,5);
c2.PrintCylinder();
return 0;
}
Output:
0 0 0 0
5 5 5 5
In Cylinder class
, I declared a Circle
object member, which calls Circle's default constructor. Cylinder c1
verifies this. Then in Cylinder c2
, I use the other Circle constructor on the Circle object.
My question - does the Circle
object in c2
use two constructors? Why does this work? Or is this merely how object declarations within classes work?
EDIT: I'm not asking about about member initialization lists.
Say I wanted to create a Circle
object in main()
using its default constructor.
int main(){
Circle c;
}
Now look at the data members of Cylinder
class.
class Cylinder{
private:
Circle circle; //Default constructor?
float height;
}
When creating a Cylinder
object, would Circle circle
call its default constructor automatically? If it does then that brings me to the 'two constructors' point.
For Cylinder c2
, that would mean its Circle
object calls its constructors Circle()
then Circle(float r, float x, float y)
due to Cylinder(float r, float x, float y, float h):circle(r,x,y),height(h){}
.