2

I've been currently learning c++ for a project of mine. At the moment, I am thinking about using a vector of pointers to a class (which I will fill with classes derived from this base class) because I want to access unique functions specific to every derived class. I am not entirely sure how to go about using it though, and from my experience with a normal vector, I understand how it can be a pain in the ass to get working, so I just want to know a couple of things:

  1. How can I add an object to the vector?

  2. How do I delete a single element in the vector?

  3. How to I access a specific object through the iterator? For instance, how do I access the functions of an object that has a pointer in the vector?

  4. How do I pass an iterator to a function that takes a pointer to an object as an argument?

Also is there anything else I should know?

chris
  • 60,560
  • 13
  • 143
  • 205
user1703993
  • 61
  • 1
  • 5
  • A tip: use a vector of smart pointers instead of raw ones. The first two questions can be answered easily with a `std::vector` reference, and the third with a reference on the random-access iterator (which is the one the vector uses). Learning how to use references is a huge aid in programming. – chris Sep 28 '12 at 04:01

1 Answers1

1

Example setup,

class Base
{
};

class DerivedOne : public Base
{
};

class DerivedTwo : public Base
{
};

std::vector<Base*> ptrVec;

To add,

ptrVec.push_back(new DerivedOne());
ptrVec.push_back(new DerivedTwo());

To delete,

std::vector<Base*>::iterator it;
/* Make sure it points to the correct element. */
delete *it;
ptrVec.erase(it);

Accessing a function is easy,

Base* ptrToObj = *it; // Assuming it points to the correct element
ptrToObj->AnyFunc(); // You can also use (*it)->AnyFunc()

Answer to your 4th question,

AnyFuncThatAcceptsObjPtr(*it); // Again assuming it points to the correct element

Also is there anything else I should know?

Yes, learn about smart pointers.

std::vector<SomeSmartPtr<Base> > smartPtrVec;

SomeSmartPtr<Base> smartPtr(new DerivedOne());
smartPtrVec.push_back(smartPtr);

smartPtrVec.erase(it); // With smart pointers, you don't need to delete explicitly
Community
  • 1
  • 1
Hindol
  • 2,924
  • 2
  • 28
  • 41
  • 3
    If you are going to suggest/advocate using pointers as container elements, atleast suggest using smart pointers instead of raw pointers. – Alok Save Sep 28 '12 at 04:39