Mega Code Archive

 
Categories / C++ Tutorial / Vector
 

Use vector to store the calsses in a hiearchy

#include <iostream> #include <string> #include <vector> using namespace std; class Person {                                 string firstName, lastName; public:     Person( string fnam, string lnam ): firstName( fnam ), lastName( lnam ) {}     virtual void print() const { cout << firstName << " " << lastName << " "; }     virtual ~Person(){}                                                }; class Employee : public Person {     string companyName; public:     Employee( string fnam, string lnam, string cnam )         : Person( fnam, lnam ), companyName( cnam ) {}     void print() const {         Person::print();         cout << companyName << " ";     }     ~Employee(){}                                                      }; class Manager : public Employee {                      short level; public:     Manager( string fnam, string lnam, string cnam, short lvl )         : Employee( fnam, lnam, cnam ), level( lvl ) {}     void print() const {       Employee::print();       cout << level;     }     ~Manager(){}                                   }; int main() {     vector<Employee*> empList;     Employee* e1 = new Employee( "A", "B", "C" );     Employee* e2 = new Employee( "D", "E", "F" );     Employee* m3 = new Manager("G", "H", "I" , 2);     Employee* m4 = new Manager("J", "J", "L", 2);     empList.push_back( e1 );     empList.push_back( e2 );     empList.push_back( m3 );     empList.push_back( m4 );     vector<Employee*>::iterator p = empList.begin();     while ( p < empList. end() ) {                         (*p++)->print();                                   cout << endl;     }     delete e1;     delete e2;     delete m3;     delete m4;     return 0; }