is it possible to use a method of an abstract class? how can i use a method of a class without having an instance?
If you declare a method as static
, you can call it directly without needing a class instance. Otherwise you will need to have an instance of a derived class.
Since an abstract class cannot be instantiated directly, you cannot call a method of an abstract class directly unless it is a static method. But you can call a static method of an abstract class directly, here is a quick example:
#include <iostream>
#include <ostream>
#include <fstream>
using namespace std;
class stest{
public:
static void test();
virtual void a() = 0;
};
void stest::test(){ cout << "test\n"; }
int main(){
stest::test();
return 0;
}
Alternatively, if you have an instance of a class that is derived from an abstract class, you can treat it as an instance of the abstract class, and can call any methods on it.
Abstract class doesn't imply you don't have an instance, it implies that the runtime type of the instance is actually some derived class that provides implementations for the pure virtual functions in the abstract base class. But not all member functions of an abstract class have to be pure virtual, you can have a mix of concrete and abstract functions.
When you call member functions "on the abstract class", all virtual functions, including the pure virtual ones, are called polymorphically. So the override defined in the derived class gets executed. Non-virtual functions call the definition in the base class, you can't have pure concrete functions so even an abstract class has to provide implementation for non-virtual functions.
It's even possible for a pure virtual function to have an implementation provided by the abstract base class. An override still has to be provided, but then the override can call the base class implementation.