As a Java programmer, C++ abstract classes are somehow weird! (Yes, they are!)
To understand them, we have to look at the header and implementation files separately. Let’s start with the base (abstract) class header file:
class AbstractBaseClass {
public:
AbstractBaseClass();
~AbstractBaseClass();
virtual void printMe();
virtual int getNumber() = 0;
};
The important thing here is that you will have to declare the abstract methods as virtual and assign them a 0 (Null Pointer). The class itself does not have any special declarations itself. So in the example above we have one abstract function (getNumber()) which makes our class to be abstract!
Within the implementation file you leave out all virtual functions that were assigned the null pointer (0):
AbstractBaseClass::AbstractBaseClass() {}
AbstractBaseClass::~AbstractBaseClass() {}
void AbstractBaseClass::printMe() {
std::cout < < "My number is: " << getNumber() << std::endl;
}
Now, let’s take a look into the header file of an inherited class:
class ConcreteClass : public AbstractBaseClass {
public:
ConcreteClass();
~ConcreteClass();
virtual int getNumber();
};
It is important to know that you will have to redeclare the function without assigning the null pointer within the header file! Otherwise the compiler will throw an exception whenever you try to instantiate a object of the concrete type!
The implementation file is straight-forward:
ConcreteClass::ConcreteClass() {}
ConcreteClass::~ConcreteClass() {}
int ConcreteClass::getNumber() {
return 1;
}
To use you concrete class you will have to create it using its own constructor. If you simply want to work with the interface (the abstract base class) then you will have to cast the newly created instance before assigning it to a pointer variable:
AbstractBaseClass* ref = (AbstractBaseClass*) new ConcreteClass();
PS: Keep in mind that polymorphism in C++ only works with pointer variables!












hehe. i bet they do and not seeing the powerful mechanism behind it.
Sounds like you’re having lots of fun
BTW: I read that C++ Programmers consider polymorphism is a bad thing, since polymorphic method calls are slower then regular method calls, so you better don’t use it!