May 6, 2014 at 8:30pm UTC
Hello,
Trying to make sure I thoroughly understand the tutorial regarding classes and member initialization given on this site.
Looking at this short program:
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
// 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;
}
Does "Circle(double r) : radius(r)..." (8th line down) initialize radius to a yet-to-be-set value equal to r?
I think specifically... does "radius(r)" assign a value to radius equal to the statement "radius = r;"?
Thanks
Last edited on May 6, 2014 at 8:31pm UTC
May 6, 2014 at 8:33pm UTC
Yeah, it's an initialisation list.
In terms of assignments, it's essentially the same as this:
1 2 3 4
Circle::Circle(double r)
{
radius = r;
}
Last edited on May 6, 2014 at 8:33pm UTC
May 7, 2014 at 2:41pm UTC
Thanks much.
I thought this was the case (in both of your replies regarding lines 8 and 21) just wanted to make sure.