Thursday, November 27, 2003

Re: Polymorphism

ok .. try this

#include < iostream >
// remember to remove the spaces .. if i put it normally it takes it as a html tag
#include < vector >
using namespace std;

class Base {
public:
virtual void pr() { cout << "Base" << endl;}
};

class Derv : public Base {
public:
void pr() { cout << "Derived" << endl; }
};

class Derv1 : public Derv {
public:
void pr() { cout << "Derived 1" << endl; }
};

int main()
{
vector< Base* > ptr;
ptr.push_back(new Base());
ptr.push_back(new Derv());
ptr.push_back(new Derv1());

for(vector< Base* >::iterator g = ptr.begin(); g != ptr.end(); ++g)
(*g)->pr();

cout << "\nNow going to Derv*\n\n";

vector< Derv* > ptr1;
ptr1.push_back(new Derv());
ptr1.push_back(new Derv1());

for(vector< Derv* >::iterator h = ptr1.begin(); h != ptr1.end(); ++h)
(*h)->pr();

//system("PAUSE"); //only windows
return 0;
}

hrishi, if what u r saying is true then the second vector's elements shouldn't show polymorphic behaviour but it does .. try it

dinesh.

No comments: