-2

I have some code that was given to me to finish but a few things are unfamiliar to me. First of all, what's the point of the member initializer in the first function?

class Circle {
private:
    double r;

public:
    Circle(double radius) : r(radius) {}

    double get_perimeter()
    {
        return 2*PI*r;
    }

    double get_radius()
    {
        return get_perimeter()/2*PI;
    }
};

and then in my main() function:

int main()
{
    double radius;
    cin >> radius;

    Circle c(radius);

    cout << c.get_radius << endl;


    return 0;
}

The Circle c(radius); line makes no sense to me. Can someone narrate me those few lines that I addressed?

dwvaxaz
  • 49
  • 1
  • 9
  • You already seem to know the term _'member initializer'_, so what you're actually asking about? – πάντα ῥεῖ Nov 09 '14 at 15:32
  • Please re-read before marking as dupe. – dwvaxaz Nov 09 '14 at 15:32
  • 1
    No need to re-read, the answers in the dupe well explain what's going on. Besides `cout << c.get_radius << endl;` doesn't compile (should be `cout << c.get_radius() << endl;`), `Circle c(radius);` creates a new `Circle` instance and initializes the `radius` with the value just entered by the user. – πάντα ῥεῖ Nov 09 '14 at 15:35

1 Answers1

0
Circle(double radius) : r(radius) {}

The point of the member initializer, r(radius), is to initialize the member r, of course! This line defines the constructor of Circle. The constructor takes an argument of type double and the initialises the member r with that value.

Circle c(radius);

This declares a variable c with type Circle and passes radius to its constructor. Compare it to std::string str("Foo"); or even int x(5); - these are all of the same form.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324