#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    14
    Rep Power
    0

    C++ Problem with inheritance and template


    The problem is as follows. When I place a derived class object (the CEO class below)into a template collection class (in this case vector) of type base class (Employee class), how do I call the functions defined in the derived class? I have tried explicit downcasting with dynamic_cast as well as just trying to use polymorphism with a base-class pointer - neither of these approaches seem to work. Below are the parts of the code that are proving problematic.

    ostream &operator<<(ostream &output, Employee &employee)
    {
    Employee* empPtr = 0;
    empPtr = &employee;
    output << "\nName:"
    << empPtr->income_calculator();//income_calculator is a virtual function, defined for every class separately, I want to access the CEO version of this function
    return output;
    }//overloaded output operator

    istream &operator>>(istream &input, CEO &employee)
    {
    double bonus;
    cout << "Input CEO's bonus:\n";
    input >> bonus;
    employee.setBonus(bonus);

    return input;
    }//end of input operator for CEO

    void EmployeeDatabase::addCEO(vector <Employee> &employees)
    {
    CEO bob;
    cin >> bob;
    employees.push_back(bob);

    }//end of addCEO function
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2009
    Posts
    45
    Rep Power
    7
    Remember to use CODE tags when posting your code.
    Originally Posted by electriceel
    I have tried explicit downcasting with dynamic_cast as well as just trying to use polymorphism with a base-class pointer - neither of these approaches seem to work.
    In vector you need to store pointers to objects, not object themselfs.
    Code:
    void EmployeeDatabase::addCEO(vector <Employee *> &employees)
    {
        CEO *bob = new CEO; // dynamic allocation
        cin >> *bob;
        employees.push_back(bob); // vector of pointers
    }//end of addCEO function
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    14
    Rep Power
    0
    Originally Posted by DRK82
    Remember to use CODE tags when posting your code.In vector you need to store pointers to objects, not object themselfs.
    Code:
    void EmployeeDatabase::addCEO(vector <Employee *> &employees)
    {
        CEO *bob = new CEO; // dynamic allocation
        cin >> *bob;
        employees.push_back(bob); // vector of pointers
    }//end of addCEO function
    Thanks for the feedback. It took a while, but finally converted everything to be stored as pointers, and ironed out the problems. c++ does not allow for casting of user-defined objects without an explicit casting constructor (although Java does).

IMN logo majestic logo threadwatch logo seochat tools logo