I'm trying to derive a class from a Base that has a friend function defined. I want to create a friend function for my derived class that makes use of the Base's friend function, but preserves the type of my Derived class:
#include<algorithm>
class Base
{
public:
Base(int i, int j, int k)
{
vect[0] = i;
vect[1] = j;
vect[2] = k;
}
~Base();
friend Base myMin (const Base& argA,
const Base& argB);
protected:
// Member data
int vect[3];
};
class Derived : public Base
{
public:
Derived(int i, int j, int k)
:
Base(i,j,k)
{
}
~Derived();
friend Derived doSomething(const Derived& argA,
const Derived& argB);
};
Base
myMin (const Base& argA,
const Base& argB)
{
int i = std::min(argA.vect[0], argB.vect[0]);
int j = std::min(argA.vect[1], argB.vect[1]);
int k = std::min(argA.vect[2], argB.vect[2]);
return Base(i,j,k);
}
Derived doSomething(const Derived& argA,
const Derived& argB)
{
// Does other stuff too...
return myMin(argA, argB);
}
int main(int argc, char *argv[])
{
Derived testA(2,4,6);
Derived testB(3,3,7);
doSomething(testA,testB);
return 0;
}
I understand why this doesn't work (doSomething is given a Base to return, but is told to return Derived), and that this probably isn't very good C++ form. My Base class has a ton of friend functions similar to this, is there a way to make use of the friend functions with my Derived class without having to modify them?
Thank you
Edited: The error, for reference, is:
base.H: In function ‘Derived doSomething(const Derived&, const Derived&)’:
base.H:50:26: error: could not convert ‘myMin(const Base&, const Base&)((* &(& argB)->Derived::<anonymous>))’ from ‘Base’ to ‘Derived’
return myMin(argA, argB);