Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
  }
}

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top