I recently started learning C++ and have been using cplusplus.com's tutorials to learn. I got to the classes section, and saw how to initialize members without typing it in the constructor's body. This seemed simple at first, but their example left me confused. Here it is:
// member initialization
#include <iostream>
using namespace std;
class Circle {
double radius;
public:
Circle(double r) : radius(r) { }
double area() {return radius*radius*3.14159265;}
};
class Cylinder {
Circle base;
double height;
public:
Cylinder(double r, double h) : base (r), height(h) {}
double volume() {return base.area() * height;}
};
int main () {
Cylinder foo (10,20);
cout << "foo's volume: " << foo.volume() << '\n';
return 0;
}
The part that confuses me is the Cylinder class, specifically:
Cylinder(double r, double h) : base (r), height(h) {}
Earlier in the class, a member object called "base" of type Circle was declared. Then, in the cylinder constructor, this "base" object was set to "r", which is a double:
base (r), height(h) {}
My question is, how could the member "base" be initialized to a double, when it is of type "Circle"? Also, I tried doing what is (what I think is) essentially the same thing, but instead I initialized "base" in the constructor's body:
Cylinder(double r, double h)
{
base = r;
height = h;
}
This left me with the compilation error: "error: no matching function for call to 'Circle::Circle()'"
If someone could clear up this confusion for me, I would greatly appreciate it. Thanks.