Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

Correctly set return of a function between base and derived class

General Tech Bugs & Fixes
Max. 2000 characters
Replies

usr_profile.png
NeelKamal Jha

User

( 7 months 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

usr_profile.png
Garry Buttler

User

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

what's your interest


forum_ban8_5d8c5fd7cf6f7.gif