60

I have a C++ vector. I want the vector to hold a variable number of objects.

Visual Studio 2012 is giving me an error:

Error: type name is not allowed

From this C++ code:

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

class testObject{
private:
   int someInt;
public:
   testObject(int a){ someInt=a; }
   void show() { cout<<someInt<<endl; }
};

int main()
{
    vector<testObject> testVector;
    cout << "Initial size: " << testVector.size() <<endl;

    for ( int i = 0; i < 3; i++ )
        testVector.push_back(testObject(3));
    cout << "New size: " << testVector.size() << endl;

    for ( int j = 0; j < 3; j++ )
        testVector[ j ].show();

    system("pause");
}    

But here's another sample of code that looks the same but it's not working.

void Dealer::setNumberOfPlayers( const int tNumber )
{
    for ( int i = 0; i < tNumber; i++ )
        vectorOfGamers.push_back(Player); // Player is a class that I created
}

Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that? As I know, all objects in vector should be of one type.

4
  • 8
    +1 for a well-posed question (your English is quite good). Commented Apr 4, 2013 at 3:30
  • 3
    create an instance of Player. Commented Apr 4, 2013 at 3:31
  • 1
    Duplicate however, answers to both these questions can be found easly via google or even here on SO. Commented Apr 4, 2013 at 3:42
  • 4
    I really googled before asking this question. Maybe my keywords for searching were not accurate enough :(. Commented Apr 4, 2013 at 3:49

5 Answers 5

81

To answer the first part of your question, you must create an object of type Player before you can use it. When you say push_back(Player), it means "add the Player class to the vector", not "add an object of type Player to the vector" (which is what you meant).

You can create the object on the stack like this:

Player player;
vectorOfGamers.push_back(player);    // <-- name of variable, not type

Or you can even create a temporary object inline and push that (it gets copied when it's put in the vector):

vectorOfGamers.push_back(Player());    // <-- parentheses create a "temporary"

To answer the second part, you can create a vector of the base type, which will allow you to push back objects of any subtype; however, this won't work as expected:

vector<Gamer> gamers;
gamers.push_back(Dealer());    // Doesn't work properly!

since when the dealer object is put into the vector, it gets copied as a Gamer object -- this means only the Gamer part is copied effectively "slicing" the object. You can use pointers, however, since then only the pointer would get copied, and the object is never sliced:

vector<Gamer*> gamers;
gamers.push_back(new Dealer());    // <-- Allocate on heap with `new`, since we
                                   // want the object to persist while it's
                                   // pointed to
Sign up to request clarification or add additional context in comments.

6 Comments

@eoLithic: It worked in the first sample because it was creating a temporary object (the "type(constructor-arguments)" syntax) and passing that in; despite the similarity in syntax, it has a very different meaning ;-)
Is it possible to do the last part without allocating it on heap (and still have polymorphism)?
@mtahmed: Well, it doesn't technically have to be allocated on the heap -- it's the fact that it's accessed through a pointer that gives it the possibility of polymorphism (while being copyable without slicing). You can take the address of objects that are allocated on the stack, too -- but you have to be careful to only use them before they're destroyed (that goes for the heap allocated ones too of course, but it's harder to accidentally destroy those before you're done using them).
I see. What I was moreso asking about was whether it's possible to push back an object without the slicing ... whether there was some neat trick to achieve that without doing explicit allocation (or using pointers to objects on volatile stack).
@mtahmed: Nope, sorry. When you add an object to a vector, it creates a new object of the templated type (either on the spot via emplacement, or with a copy or move of an object you give it). No matter how it's done, the object only has room for its own members (the size of the object is computed at compile time, remember), not any of those of an inherited class, so derived objects would get sliced. (And as for virtual methods, those too would be inaccessible because the vtable would be for the wrong (base) type.)
|
5

Question 1:

   vectorOfGamers.push_back(Player)

This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:

vectorOfGamers.push_back(Player(name, id)) 
  //^^assuming name and id are parameters to the vector, call Player constructor
  //^^In other words, push `instance`  of Player class into vector

Question 2:

These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?

Yes you can. You can create a vector of pointers that points to the base class Gamer. A good choice is to use a vector of smart_pointer, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?

Comments

1

You cannot insert a class into a vector, you can insert an object (provided that it is of the proper type or convertible) of a class though.

If the type Player has a default constructor, you can create a temporary object by doing Player(), and that should work for your case:

vectorOfGamers.push_back(Player());

Comments

1

I know the thread is already all, but as I was checking through I've come up with a solution (code listed below). Hope it can help.

#include <iostream>
#include <vector>

class Box
{
    public:

    static int BoxesTotal;
    static int BoxesEver;
    int Id;

    Box()
    {
        ++BoxesTotal;
        ++BoxesEver;
        Id = BoxesEver;
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") initialized." << std::endl;
    }

    ~Box()
    {
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") ended." << std::endl;
        --BoxesTotal;
    }

};

int Box::BoxesTotal = 0;
int Box::BoxesEver = 0;

int main(int argc, char* argv[])
{
    std::cout << "Objects (Boxes) example." << std::endl;
    std::cout << "------------------------" << std::endl;

    std::vector <Box*> BoxesTab;

    Box* Indicator;
    for (int i = 1; i<4; ++i)
    {
        std::cout << "i = " << i << ":" << std::endl;
        Box* Indicator = new(Box);
        BoxesTab.push_back(Indicator);
        std::cout << "Adres Blowera: " <<  BoxesTab[i-1] << std::endl;
    }

    std::cout << "Summary" << std::endl;
    std::cout << "-------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Adres Blowera: " <<  BoxesTab[i] << std::endl;
    }

    std::cout << "Deleting" << std::endl;
    std::cout << "--------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Deleting Box: " << i+1 << " (" <<  BoxesTab[i] << ") " << std::endl;
        Indicator = (BoxesTab[i]);
        delete(Indicator);
    }

    return 0;
}

And the result it produces is:

Objects (Boxes) example.
------------------------
i = 1:
Box (1/1/1) initialized.
Adres Blowera: 0xdf8ca0
i = 2:
Box (2/2/2) initialized.
Adres Blowera: 0xdf8ce0
i = 3:
Box (3/3/3) initialized.
Adres Blowera: 0xdf8cc0
Summary
-------
Adres Blowera: 0xdf8ca0
Adres Blowera: 0xdf8ce0
Adres Blowera: 0xdf8cc0
Deleting
--------
Deleting Box: 1 (0xdf8ca0) 
Box (1/3/3) ended.
Deleting Box: 2 (0xdf8ce0) 
Box (2/2/3) ended.
Deleting Box: 3 (0xdf8cc0) 
Box (3/1/3) ended.

Comments

0
// create a vector of unknown players.
std::vector<player> players;

// resize said vector to only contain 6 players.
players.resize(6);

Values are always initialized, so a vector of 6 players is a vector of 6 valid player objects.

As for the second part, you need to use pointers. Instantiating c++ interface as a child class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.