Initializing class member variables

what does these instructions mean when it says "initialize pi with the value 3.14" ..... how can i initialize that variable? The instructions don't list any functions that i can use to set pi to 3.14...... so is this telling me to initialize the pi variable inside the class like i have done below or is there some other way i can do this

1
2
3
4
5
6
7
8
9
10
11
12
class Circle
{
	private:
		double radius;
		double pi = 3.14;
	public:
		Circle();
		Circle(int r);
		void setRadius(int r);
		double getRadius() const;
		double getArea() const;
};



Write a Circle Class that has the following member variables:

radius: a double
pi: a double initialized with the value 3.14

The class should have the following member functions:

Default Constructor - a default constructor that sets radius 0.0
Constructor - accepts the radius of the circle as an argument
setRadius - A mutator method for the radius variable
getRadius - An accessor method for the radius variable
getArea - Returns the area of the circle
pi makes more sense as a constant that is shared between all Circle instances.

You could make it static variable
static const double pi;
that you define in a source file
const double Circle::pi = 3.14;

In C++11 you can define it inside the class definition by using the constexpr keyword.
static constexpr double pi = 3.14;
You can also initialise class member variables in the constructor functions for that class.
To repeat http://www.cplusplus.com/forum/general/87622/#msg470047

1
2
3
4
5
6
7
8
9
10
struct A
{
    int value = 0 ;
    std::string name = "anon" ;

    A() {} // value initialized with 0, name initialized with "anon"
    A( int i ) : value(i) {} // value initialized with i, name initialized with "anon"
    A( const char* n ) : name(n) {} // value initialized with 0, name initialized with n
    A(  int i, const char* n ) : value(i), name(n) {} // value initialized with i, name initialized with n
};
Topic archived. No new replies allowed.