-
Why wont this compile:
What is wrong with this code:
Code:
#include <iostream>
using namespace std;
class AbstractClass
{
public:
virtual void Func();
virtual void Func(int x) = 0;
};
class DerivedClass : public AbstractClass
{
virtual void Func(int x);
};
void AbstractClass::Func()
{
Func(3);
}
void DerivedClass::Func(int x)
{
cout << " x is " << x << "\n";
}
int main(void)
{
DerivedClass d;
d.Func();
}
When I compile it it says no matching function call to DerivedClass::Func().
If I change the following it works:
Code:
int main(void)
{
AbstractClass *d = new DerivedClass;
d->Func();
delete d;
}
Or, if I change the name Func(int x) to Foo(int x) it works. Why cant I overload Func with a pure virtual function?
Thanks,
Bob
-
It may seem confusing, but function pointers a.k.a virtual functions aren't considered inherited from the child class even though they are! You'll need to interprete the derived class as its base in order to use a not overlapped virtual function ( overlapped by child ).
-
virtual is really a red herring here. Even if you had
Code:
class A {
public:
void foo();
};
class B : public A {
public:
void foo(int x);
};
//later
B bar;
bar.foo(); //won't work
The "new" foo in class B will hide the "old" foo in class A.
-
-
Quote:
Originally Posted by
godly 20
....
Some parts of C++ can be confusing, but that's how it is and we have to (cope?) with them.
-
This is name hiding. To make the base classes Func visible in the derived class:
Code:
class DerivedClass : public AbstractClass
{
public:
using AbstractClass::Func;
virtual void Func(int x);
};
You might also consider renaming the overloads.