Correctly set return of a function between base and derived class

General Tech Bugs & Fixes 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

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

profilepic.png
manpreet 2 years ago

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]);
}

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.