Reputation: 109
I have a problem with the following task. I have two classes Config
(base) and Ising
(derived) each of which has a std::array
of 12 bool
. I created a function Incr()
which does the following
-if the i-th elem of the array is false Incr()
sets it as true and exit;
-if the i-th elem of the array is true sets it as false and then moves to the i+1-th elem.
Incr()
must work if I call it twice (as in foo.Incr().Incr()
) so I thought it should return a reference to a Config
I am now required (it is an exercise )to create an std::vector
of 4096 Ising
object all created via application of Incr()
to the preceding Ising
object. Fact is that this function returns a Config
...
I can set it to return a Ising
but this seems a very poor design choice to have a base class method which returns an object of its derived class.
I was wondering whether there is a more elegant way to do this
This is what I am working with:
class Config {
public:
//ctor
Config(){
for(auto i=m_arr.begin(); i !=m_arr.end(); i++){
*i = false;
}
};
//incr function
Config& Incr(){
for(auto i = m_arr.begin(); i != m_arr.end(); i++){
if(*i ==false){*i = true; return *this;}
else{
*i=false;
}
}
return *this;
};
private:
std::array<bool,12> m_arr;
};
class Ising: public Config{
public:
Ising(double g =1): m_g(g){
};
private:
double m_g;
};
int main(){
Config f; //check ctor
Ising is(3);
is.Incr();
std::vector<Ising> vec;
vec.push_back(is);
for(int i=0; i < 4096; i++){
vec.push_back(vec[i].Incr());
}
return 0;
}
Thanks to everyone who will help
Upvotes: 1
Views: 53
Reputation: 87959
What's wrong with this? No need for a redesign.
Ising is(3);
is.Incr();
std::vector<Ising> vec;
vec.push_back(is);
for (int i = 0; i < 4096; i++) {
vec[i].Incr();
vec.push_back(vec[i]);
}
Upvotes: 2