andy wrote:
The under lining reason why I need to do this is to utilize the
constructor of one class in a second class - thereby optimizing the
code by avoiding duplication.
Take this example:
Constructor of first class:
Class1::Class1( void )
{
a = 0;
}
Instead of duplicating this I would like Class2 to use this same
constructor:
Class2::Class2( void )
{
//I would like code here that would pass an array to the Class1
constructor and if the array was 5 in size then each position in the
array would be initialized with a=0
}
I hope this is a little clearer ?
Yes, its clearer except that you've missunderstood one fundamental
isse, with a std::vector, the code would be both much easier to
implement and (surprise!) a std::vector is faster than a primitive
array.
I can achieve the entire code below with 1 line in main using a
std::vector. Yes: just one line.
std::vector< double vn(11.1, 5);
Except, of course, that the vector is dynamic, resizeable, reserveable.
Note that you can't template Class1 if you choose to have
floating-points because a floating literal constant can't be in a
template parameter list. Something else a std::vector has no issues
with.
#include <iostream>
#include <stdexcept>
class Class1 {
double d; // modify to your convenience
public:
Class1() : d(11.1) { // default - set it to whatever you need
std::cerr << "Class1()\n";
}
friend std::ostream&
operator<<( std::ostream& os, const Class1& r_c1 ) {
return os << r_c1.d;
}
};
// T is your target type
// Size is the array's injected size
template < typename T, const size_t Size >
class Container {
T array[ Size ];
public:
Container() { }
// size_t size() const
size_t size() const {
return Size;
}
// at(index)
T& at( const size_t index ) {
if ( Size <= index ) // bounds check
throw std::range_error(
"Container index out of range."
);
return array[ index ];
}
};
int main() {
try {
Container< Class1, 5 container;
for ( size_t i = 0; i < container.size(); ++i ) {
std::cout << "container[" << i << "] = ";
std::cout << container.at( i ); // using accessor at()
std::cout << std::endl;
}
} catch ( const std::exception & r_e ) {
std::cerr << "error: ";
std::cerr << r_e.what() << std::endl;
}
}
/*
Class1()
Class1()
Class1()
Class1()
Class1()
container[0] = 11.1
container[1] = 11.1
container[2] = 11.1
container[3] = 11.1
container[4] = 11.1
*/