C++ examples for Class:Member Function
Demonstrates use of default arguments in class member functions.
Sphere(float xcoord, float ycoord = 2.0, float zcoord = 2.5, float radius = 1.0) { x = xcoord; y = ycoord; z = zcoord; r = radius; }
You can create a sphere with the following instructions:
Sphere s(1.0); // Use all default Sphere t(1.0, 1.1); // Override y coord Sphere u(1.0, 1.1, 1.2); // Override y and z Sphere v(1.0, 1.1, 1.2, 1.3); // Override all defaults
Example,
#include <iostream> using namespace std; #include <math.h> const float PI = 3.14159; // Approximate value of pi. // A sphere class. class Sphere/* w ww. j ava 2s. c o m*/ { public: float r; // Radius of sphere float x, y, z; // Coordinates of sphere Sphere(float xcoord, float ycoord = 2.0, float zcoord = 2.5, float radius = 1.0) { x = xcoord; y = ycoord; z = zcoord; r = radius; } ~Sphere() { cout << "Sphere (" << x << ", " << y << ", " << z << ", " << r << ") destroyed\n"; } inline float volume() { return (r * r * r * 4 * PI / 3); } float surface_area() { return (r * r * 4 * PI); } }; void main() { Sphere s(1.0); // use all default Sphere t(1.0, 1.1); // override y coord Sphere u(1.0, 1.1, 1.2); // override y and z Sphere v(1.0, 1.1, 1.2, 1.3); // override all defaults cout << "s: X = " << s.x << ", Y = " << s.y << ", Z = " << s.z << ", R = " << s.r << "\n"; cout << "The volume of s is " << s.volume() << "\n"; cout << "The surface area of s is " << s.surface_area() << "\n"; cout << "t: X = " << t.x << ", Y = " << t.y << ", Z = " << t.z << ", R = " << t.r << "\n"; cout << "The volume of t is " << t.volume() << "\n"; cout << "The surface area of t is " << t.surface_area() << "\n"; cout << "u: X = " << u.x << ", Y = " << u.y << ", Z = " << u.z << ", R = " << u.r << "\n"; cout << "The volume of u is " << u.volume() << "\n"; cout << "The surface area of u is " << u.surface_area() << "\n"; cout << "v: X = " << v.x << ", Y = " << v.y << ", Z = " << v.z << ", R = " << v.r << "\n"; cout << "The volume of v is " << v.volume() << "\n"; cout << "The surface area of v is " << v.surface_area() << "\n"; return; }