Gary Wessle wrote:
Quote:
Hi
>
Stroustrup p.312 second paragraph after the code.
" To get polymorphic behavior in C++, the member function called must
be virtual and objects must be manipulated through pointers or
references."
>
the code below fulfills the virtual part, can someone please show me
how the second part is done? i.e, manipulating the object through
pointers or references.
>
thank you
>
>
//task.h
************************************************** **************
#ifndef TASK_H
#define TASK_H
#include <string>
>
class Task {
public:
virtual void print_mi()=0; // print menu item
};
>
class Thr_task : public Task {
std::string m_item;
public:
Thr_task(const std::string&);
void print_mi();
};
>
#endif
>
>
//task.cpp
************************************************** **************
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
>
using namespace std;
>
#include "task.h"
>
Thr_task::Thr_task(const string& n) :
m_item(n)
{
}
>
void Thr_task::print_mi() {
cout << m_item << endl;
}
>
>
//main.cpp
************************************************** **************
#include "task.h"
using std::vector;
using namespace std;
>
int main() {
Thr_task t1("preform Thread task.");
>
vector<Task*vTp;
|
In the above container, you are storing pointers to *any* type derived
from Task.
The compiler will complain if print_mi() is not available for type Task
and derivatives.
loads the element's address into a new slot, C++ compiler does that
with a type check.
Here, the element at vTp[0] is a pointer to a Task derivative.
Therefore, the call to print_mi() is -polymorphic.
Thats probably implemented using a virtual table on your platform, but
not necessarily.
p_element->vtable_lookup->behaviour()
If you need a decent description of that process, download Eckell's
Thinking in C++ Vol1 at mindview and read the first few chapters.
http://mindview.net/Books/TICPP/ThinkingInCPP2e.html