views:

208

answers:

3

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
i want to declare void f(int) in the derived clas, which was declared as virtual void f()=0 in the base class
cemregoksu
Your problem is that you need to have f(int)=0 in your base class then.
Brian R. Bondy
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
@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
+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
isn't it considered as override?
cemregoksu
@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
@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
I didn't know that. thank you both=)
cemregoksu
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