Inheritance / Virtual methods

Dec 14, 2011 at 8:23pm
Hi i have two classes class a and class b. in class a i have a method called borrow() which is quite long and uses a static variable in the method (only associated with the class) I now have class b that publicly inherits from class a. i now want to use the borrow() method but with just the static variable changed from what it was set to in class a to a new static variable which is set in class b. I am aware of using a virtual method to inherit the method into class b and then implement it with the new static variable but as far as im aware this would require writing the long method out again with just one word changed there must be an easier way to do this please help

Thanks.
Dec 14, 2011 at 8:34pm
Why don't you make your static variable a private object in a? That would eliminate any guesswork and I believe you could use a new occurance of it in b.
Dec 14, 2011 at 8:47pm
It is given as an excerise and the static variables are given and cannot be changed im kind of thinking that making the static variable protected and then setting it in the new class to what it is in the new class but then both variables will be what i set them to which is a problem. Is there a way of inheriting a method but with different variables set for the method to be used on (I dont mean parameters).
Dec 14, 2011 at 9:39pm
Suppose that there is. ¿how will you tell which variables do you want?

A possibillity is the template pattern.
1
2
3
4
5
6
double calculation(){
  double val = value();
  //...
}

virtual double value() = 0;
So you change the virtual function value, but the outline of the algorithm is in calculation which is not virtual (doesn't change)
Dec 14, 2011 at 10:21pm
Seems a good idea.

So does this mean that that in my second class i wouldnt have to write the whole borrow() method out again just would literally be:
1
2
3
4
5
6
bool borrow(){
int myValue = value();
// so i wouldnt need to write the rest of the code for the borrow method also borrow isnt virtual 
// does this matter will i still be able to implement borrow in the second class as it is now not virtual
}
virtual int value() = 50;
Dec 15, 2011 at 3:19am
You don't implement borrow in the derived class.
You just adjust whatever the methods called by borrow do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class base{
private:
  //these are helpers that will be called by borrow()
  virtual int value() = 0; //pure virtual method
  virtual double calculate(double); //default behaviour
  virtual double limit(); //default behaviour
public:
  bool borrow(); //non-virtual method
};

class derived: public base{
private:
  virtual int value(); //modifyng behaviour
};


Similar issue http://cplusplus.com/forum/general/27880/
Topic archived. No new replies allowed.