questions regarding classes and member initialization

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
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
Does "Circle(double r) : radius(r)..." (8th line down) initialize radius to a yet-to-be-set value equal to r?

Yes.

At line 21 where foo is instantiated, 10 is passed in the first argument. This is passed to Circle's constructor (via base). Circle's constructor then intializes radius to 10 (via r).

Thanks much.

I thought this was the case (in both of your replies regarding lines 8 and 21) just wanted to make sure.
Topic archived. No new replies allowed.