class MyClass
{
public:
MyClass(); // constructor that initializes MyClass
private:
std::array<double, aNumber> myVar; // array to be encapsulated
}; // end class MyClass
Now, let's say I create an array of MyClass objects:
std::array<MyClass,10> MyObject;
I want the constructor to initialize myVar, for every object, from a specific file.
That is, there is a specific file for every object.
Can I do this without compromising myVar encapsulation?
I mean, without using a setter?
class A
{
public:
A() = default ; // defaulted default constructor
// initialises to all zeroes (member initialiser)
explicit A( std::string file_name ) // reads numbers from the file into the array
{
std::ifstream file(file_name) ;
for( double& d : arr ) file >> d ;
// not that on input failure, the values remain zero
}
private:
staticconstexpr std::size_t N = 10 ;
// in-class member initialiser initialises to all zeroes
std::array< double, N > arr {} ;
};
#include <iostream>
#include <array>
#include <string>
#include <fstream>
class A // unchanged, the same as in the earlier post
{
public:
A() = default ; // defaulted default constructor
// initialises to all zeroes (member initialiser)
explicit A( std::string file_name ) // reads numbers from the file into the array
{
std::ifstream file(file_name) ;
for( double& d : arr ) file >> d ;
// not that on input failure, the values remain zero
}
private:
staticconstexpr std::size_t N = 10 ;
// in-class member initialiser initialises to all zeroes
std::array< double, N > arr {} ;
};
int main()
{
// initialise these objects from the specified files
std::array< A, 4 > my_objects { A{"file0"}, A{"file1"}, A{"file2"}, A{"file3"} } ;
// update my_objects[2] using the contents of file "new_file2"
my_objects[2] = A{ "new_file2" } ;
}