I have an abstract class with a pure virtual function f() and i want to create a class inherited from that class, and also override function f(). I seperated the header file and the cpp file. I declared the function f(int) in the header file and the definition is in the cpp file. However, the compiler says the derived class is still abstract. How can i fix it?
+1
A:
Are you declaring f(int) in your base class as pure virtual or f()?
Pure virtual functions can have definitions inside their base class. A pure virtual function simply says that the derived type must also specify their own implementations of the function f(int).
class Base
{
public:
virtual void f(int) = 0;
}
Base::f(int)
{
//some code
}
class Derived : public Base
{
public:
virtual void f(int)
{//Implementation is needed in Derived since f(int) is pure virtual
}
}
Brian R. Bondy
2010-03-27 20:41:33
i want to declare void f(int) in the derived clas, which was declared as virtual void f()=0 in the base class
cemregoksu
2010-03-27 20:43:27
Your problem is that you need to have f(int)=0 in your base class then.
Brian R. Bondy
2010-03-27 20:44:45
hmm...but i want to derive several classes and want to use different forms such as f(string), f(int) etc in different classes. so the unique solution for me is to change the function names,i think.
cemregoksu
2010-03-27 20:48:15
@cemregoksu: f(string), f(int) are completely different functions. You can for example require implementation of f() but there is no generic way to say require implementation of f(anything).
Brian R. Bondy
2010-03-27 20:56:10
+1
A:
The functions f() and f(int) do not have the same signature, so the second would not provide an implementation for the first. The signatures of the PVF and the implementation must match exactly.
anon
2010-03-27 20:42:42
@cemregoksu No, they are different functions. The "real name" of a function in C++ is its apparent name plus all the types of the functions parameters, plus the function's constness, all encoded somehow.
anon
2010-03-27 20:46:02
@cemregoksu: No they are different functions f() and f(int). They have the same name but not the same signature, and so they are different functions.
Brian R. Bondy
2010-03-27 20:46:18
A:
What about using C++ templates?
template<typename T>
class Basic{
public:
void f(T);
};
template<typename T>
Basic<T>::f(T t){
//Do something generic here
}
You can use template specialization if your function f needs to do something else when it's parameter is a specific type. I'll use string in this example.
template<>
class Basic<string>{
public:
void f(string);
};
template<>
Basic<string>::f(string t){
//Do your special thing with a string
}
Hope this helps!
PieterK
2010-04-03 10:55:15