C0D3 wrote: |
---|
So basically what it does is it let's you take one part from the parent class and if you put virtual infront of it, you can use it anywhere? |
No...
It let's you do tasks that are specific to different derived classes, without having to know exactly which derived class you're working with.
This means you can write code that works with an abstract parent class... and that code will in turn work with any derived class.
Here's another example... (this example is basically what iostream does... but nevermind that):
Let's say you have an abstract parent class called "File". This class has a pure virtual "Read" function that reads an int from the file and returns it:
1 2 3 4 5
|
class File
{
public:
virtual int Read() = 0;
};
|
Because the function is pure virtual, it has no body. It is assumed that derived classes will fill in their own body for it. But we can still call it from code.
Now let's say we have data that we want to load from a file:
1 2 3 4 5 6 7 8
|
void MyClass::Load(File* file)
{
mydata = file->Read();
otherstuff = file->Read();
for(int i = 0; i < X; ++i)
myarray[i] = file->Read();
//...
}
|
The
File
class creates an
"abstract interface" that our code can use. This class represents a
concept. The File class represents some kind of file (but we don't know exactly what kind of file), and the Read function reads from that file and returns the data.
The key here is that different kinds of files will read the data different ways.
Normal files will just read it off the disk. But what if the file is zipped or compressed or something? You could have a separate class for zipped files and just derive from File and use the same abstract interface. That way any code that reads from a
File
could also read from a
ZippedFile
because a ZippedFile "is a" File.
The actual loading code doesn't have to know or care where the data is coming from or how it's getting there.
Without polymorphism, you might have to write two entirely different loading functions. One that loads from a normal file and one that loads from a zipped file. And even then it would only work with those 2 types of files. If you add a future type later (like a .7z or .rar file, or a file over an internet connection, etc) you'll have to keep writing more and more versions of the same function.
But with polymorphism, you can just deal with that abstract interface. Future classes can be created, and any old code that uses the abstract interface will work with your new classes without you having to modify any old code.