# Classes and arrays. Initializing arrays with data values from class objects. Examples

### Contents

Search other websites:

##### 1. Initializing an array by values that are data members of the object. Example

There are cases when you need to combine variables that are members of a class object in an array. In the following example, an array is initialized, which uses the data members of the object as initializers. At the time of declaration, the data members of the object must have some meaning.

The example defines the Radius class, in which are declared:

• an internal variable named radius;
• internal private method CalcValues(), which fills with values public-variables length, area, volume;
• public internal variables of class length, area, volume, containing the corresponding values of the circumference, the area of the circle and the volume of a sphere for radius r;
• class constructors;
• access methods GetR(), SetR().

The class listing is as follows:

```// class realizing the radius of a geometric figure
{

// An internal method that forms the values of variables length, area, volume
void CalcValues(void)
{
const double pi = 3.141592653589;
length = 2 * pi * radius;
}

public:
double length; // circumference
double area; // area of a circle
double volume; // the volume of a sphere

// constructors
{
CalcValues(); // fill the variables length, area, volume
}
{
CalcValues(); // fill the variables length, area, volume
}

// access methods
int GetR(void) { return radius; }
{
CalcValues(); // fill the variables length, area, volume
}
};```

Using a class in main() or another function:

```Radius r(3); // the object r of class Radius

// initializing an array V with values that are members of the data of the object r
double V[] = {
r.length,
r.area,
r.volume
};

double x;
x = V; // x = 18.8496 - circumference
x = V; // x = 28.2743 - area of a circle
x = V; // x = 113.097 - volume of a sphere```

##### 2. Initializing the array with values that return the objects of the class. Example

Elements of an array can be initialized with values that return the methods of a certain class. The example demonstrates the initialization of the V array with values that are returned by the methods of the Radius class: Length(), Area(), Volume().

The declaration of the class has the form;

```// class that realizes the radius value of some geometric figure
{

public:
double Length()
{
return (2 * 3.1415 * radius);
}

double Area()
{
}

double Volume()
{
}

// constructors
{
}
{
}

// access methods
int GetR(void) { return radius; }
{
}
};```

Использование класса в некотором методе

```Radius r(3); // the object r of Radius class

// Initializing an array V with values that are returned by the object's methods of class r
double V[] = {
r.Length(),
r.Area(),
r.Volume()
};

double x;
x = V; // x = 18.8496 - circumference
x = V; // x = 28.2743 - area of a circle
x = V; // x = 113.097 - volume of a sphere```