Re: Newbie inheritance question
On Jul 19, 5:07 am, ke...@bytebrothers.co.uk wrote:
Hi all, I'm getting confused again, so someone please take pity and
explain. I've got something like this:
class Base
{
void do_work(string&, string&, int&);
};
class Derived : public Base
{
void do_work(char*, char*, int&);
};
int main()
{
Derived MyObj;
string sString, bString;
MyObj.do_work(aString, bString, 123);
}
This gives a compile-time error that basically says
no matching function for call to `Derived::do_work(string&, string&,
int)'
candidates are: void Derived::do_work(char*, char*, int&)
Why does the compiler not use the matching function from the Base
class? I can work around it by doing something like this:
int main()
{
Base* ptr = new Derived();
string aString, bString;
ptr->do_work(aString, bString, 123);
delete ptr;
}
but that seems to sort of defeat the purpose of inheritance, to my
newbie eyes at least.
I guess the short answer is that the Derived::do_work() method hides
the base class method. You will need to either a) add both
declarations in the Base class, or b) change the name of the Derived
class method, or c) add both declarations to the Derived class. My
example below implements options c.
Something else I want to add is that the third parameter is a
reference to an int, so you will need to pass in a variable, not a
constant. I get a compile error when I try passing the constant 123.
class Base
{
public:
virtual void do_work(string&, string&, int&);
};
class Derived : public virtual Base
{
public:
void do_work(string&, string&, int&);
void do_work(char*, char*, int&);
};
void Derived::do_work(string& a, string& b, int& c)
{
cout << a << ", " << b << ", " << c << endl;
}
void int main()
{
Derived MyObj;
string aString, bString;
int myInt = 123;
MyObj.do_work(aString, bString, myInt);
}
Jim