Call the virtual function from classes stored in a vector : object vector « vector « C++ Tutorial






#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Employee {         
    string firstName, lastName;
public:

    Employee(string fnam, string lnam) {
        firstName = fnam;
        lastName = lnam;
    }
    virtual void print() const {                                              
      cout << firstName << " " << lastName << " ";
    }
    virtual ~Employee(){}                                                     
};

class Manager : public Employee {            
    short level;
public:
    Manager(string fnam, string lnam, short lvl)
        : Employee(fnam, lnam), level(lvl) {}
    void print() const {                     
        Employee::print();
        cout << " works at level: " << level;
    }
    ~Manager(){}
};

int main()
{
    vector<Employee*> empList;
    Employee* e1 = new Employee("A", "B");
    Employee* e2 = new Employee("C", "D");
    Employee* e3 = new Manager( "E", "F", 2 );
    Employee* e4 = new Manager( "G", "H", 3 );

    empList.push_back( e1 );
    empList.push_back( e2 );
    empList.push_back( e3 );
    empList.push_back( e4 );

    vector<Employee*>::iterator p = empList.begin();
    while ( p < empList.end() ) {
        (*p++)->print();
        cout << endl;
    }
    delete e1;
    delete e2;
    delete e3;
    delete e4;
    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