I'm writing a program that creates a vector of pointer-to-objects.
How do I access the individual objects that the pointers reference from the pointer-to-objects vector?
I'm trying to call the speak() function in the class Object for each of the objects that the pointers inside the vector reference.
Thank you for your time
class Object
{
public:
void speak()
{
cout<<"Hello!"<<endl;
}
};
int main()
{
int choice;
vector<Obj*> objVector; //create empty vector of "pointer-to-object"
Object* ptrObj; //point to object
while (choice!=5)
{
cout <<"1.Create Object\n";
cout <<"2.Destroy Object\n";
cout <<"3.Print number of existing Objects\n";
cout <<"4.Tell existing Objects to say Hello\n";
cout <<"5.Quit Program"<<endl;
cout <<"Please enter your choice: ";
cin >> choice;
if (choice==5)
cout <<"\nProgram is quitting\n"<<endl;
else if (choice==1)
{
ptrObj= new Object;
ObjVector.push_back(ptrObj); //adding an Object object
}
else if (choice==2) //remove object
{
objVector.pop_back();
}
else if (choice==3)
{
cout <<"\nThere are " << objVector.size() <<" objects total.\n" << endl;
}
else if (choice==4)
{
for (int i=0; i<objVector.size(); i++)
{
????????????
}
}
}
return 0;
}
new, you should also be usingdelete. When you remove an object from the vector, you're just throwing away the pointer, but the object is still in memory, taking up space.pop_back()returns the pointer it's removing, and you should store that pointer somewhere ordeleteit, perhaps like:ptrObj=objVector.pop_back(); delete ptrObj;unique_ptr