Question about Polymorphism.
Posted: Sun May 11, 2014 4:04 pm
I've recently learned about polymorphism in C++. I get the jest of virtual members, abstract classes, and pointers to a base class. What I don't understand is the purpose of have a pointer to a base class. The resources I've read on polymorphism have all shown that you have an object from a derived class and a pointer of a base class pointing to that object, then calling some function from the pointer. What do I gain from doing that? I thought the point of inheritance was so I could call those same functions from an object of the derived class.
//basic includes and stuff
#include<iostream>
using namespace std;
//Base class
class Base {
int x, y; //variables and stuff in the Base class
public:
void SetXandY(int a, int b) { //generic function
x = a;
y = b;
}
int GetX() { return x; } //accessor functions
int GetY() { return y; }
};
//Derived Class
class Derived : public Base { //Derived class inherits from Base class
int w, h; //other members you'd add in derived classes
public:
void SetWandH(int a, int b) { //generic derived class function
w = a;
h = b;
}
int GetW() { return w; } //accessor functions
int GetH() { return h; }
};
//main function
int main() {
Derived obj; //declares an object from the derived class
Base* objpointer = &obj;
/* We can do this because the object of the Derived class
is inheriting from the Base Class. */
//now we can do this
objpointer->SetXandY(5, 20); //this will make the x and y values for obj 5 and 20 respectively
//shows us the data
cout << obj.GetX() << endl;
cout << obj.GetY() << endl;
//holds the screen
system("PAUSE");
//end of main
return 0;
}
This works and I know why it works. I understand all of it. But why do I need a pointer at all? I can call obj.SetXandY() without making a pointer and it still preforms the same. So there isn't any need for objpointer.