I am trying to solve for the root of a function in an interval [a,b].
class base
{
protected:
float a, b;
public:
base () : a(0.0), b(1.0) //constructor
float f(float x)
{//supply function
...
...
}
float root(float a, float b)
{//solve for the root in the interval [a,b]
...
...
}
};
//Now I want to define a derived class which would be able to modify [a, b] and supply a new function f(x).
class derived : private base
{
private:
float a;
float b;
public:
derived () : a(2.0), b(4.0) //constructor
float f(float x)
{//define new function
...
...
}
};
//Main
int main()
{
derived d;
float x;
//Hoping x is the root for the new function supplied in the derived class
x = d.root(d.a, d.b);
return 0;
}
The code does not work mainly because, since "root" is a base class member it can only see the other base class members (i.e. f(x) in the base class). So the question is how can it take the member function of the derived class.
The other question is: since a, b are protected members of base class they are accessible by the derived class. So how do I initialize them in the derived class without redefining them as private members again there?
You are right about passing a and b in root(), it should automatically be able to access those, but because I could not make those limits pass for the derived class (where I want to modify their values, hence they are protected in the base class) I am explicitly passing those as arguments. That's why I asked my second question, how do I automatically pass their modified values for derived class to the function root()?
ico
I think what you are trying to ask is why can I not use the protected member variable in base, while doing something inside the derived class? If this is your question you need to change your inheritance to public.
Private inheritance will make everything in the base class inaccessible to the derived.
You could use protected inheritance here to still access of those protected members.