Use vector to store the calsses in a hiearchy : object vector « vector « C++ Tutorial






#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;
}








16.31.object vector
16.31.1.Store a class object in a vector.
16.31.2.vector with 10 objects
16.31.3.Object vector
16.31.4.Call member function for each element in vector
16.31.5.Call the virtual function from classes stored in a vector
16.31.6.Use vector to store the calsses in a hiearchy
16.31.7.Use vector as an array for user-defined object