fbdg
fbdg

Reputation: 11

Polymorphic vector

Hi can someone please explain what is wrong with the following code?I am first including the child of an abstract class in another class which will be using this child.

#include "child.h"

Then I'm populating the 2d vector below with pointers which point to instances of the child.

vector<vector<abstractitem*>*>vec;

I am then using this class function in my class. The function get is found in the abstract class.

void fn::getall()
{
    for (int i=0;i<m_nrows;i++)
    {
        for(int j=0;j<m_ncolumns;j++) 
        {   

            vec[i][j]->get(); //error on this line: do you intend to use . instead?

        } 
        printf("\n");
    }  

} 

Your help will be much appreciated.

Upvotes: 0

Views: 334

Answers (2)

IanPudney
IanPudney

Reputation: 6031

Notice that your outer vector is a vector of pointers to vectors, not a vector of vectors. This means that your function call resolves like this:

vec[i][j]->get();
(vector<abstractitem*>*)[j]->get();
*(vector<abstractitem*>* + j)->get();
vector<abstractitem*> ->get();

You can see the error in the last line: your get() function is attempting to run on a vector, but you wrote it expecting it to be an abstractitem*.

Either change your declaration to a vector of vectors, or add a dereference to your call:

vector<vector<abstractitem*>> vec; //option 1
(*vec[i])[j]->get(); //option 2

Upvotes: 1

sp2danny
sp2danny

Reputation: 7687

you either need to change

vector<vector<abstract*>*> vec;

into

vector<vector<abstract*>> vec;

or change

vec[i][j]->get();

into

(*vec[i])[j]->get();

the former is probably better, there is no good reason why the outer vector should hold pointers to the inner vector.

even better would be using smart pointers:

vector<vector<shared_ptr<abstract>>> vec;

it frees you completely from object memory management

Upvotes: 3

Related Questions