I am learning polymorphism and I am familiar with php.
I came across this excellent example from https://stackoverflow.com/a/749738/80353. reproduced below.
How
Well, you can use a pointer with abstract classes using pure virtual methods like so:
class Polygon {
public:
virtual void setValue(int k) = 0; // Declaring our pure virtual method.
};
class Rect : public Polygon {
public:
virtual void setValue(int k); = 0; // Declaring the pure virtual method again.
};
Rect::setValue(int k) { // You must create a setValue() method for every class, since we made a pure virtual method. This is the Polymorphic part.
// Code in here that setValue() method executes.
int foo = a;
std::cout << foo << std::endl;
}
Now you can access the methods declaring object pointers.
int main() {
Polygon* pSomePolygon = nullptr; // Assuming using C++11.
Rect* pRect = new Rect; // Declare our object.
pSomePolygon = pRect; // Point our pointer to object 'pRect'.
pSomePolygon->setValue(18); // Pointer accesses pRect and uses the pure virtual method.
delete pRect; // Clean up!
return 0;
}