0

I'm trying to create a dynamic array of objects, similar to ArrayLists in Java. I'm new at C++ and can't get it to work.

class Album{

private:

public:
    void addPhoto(Photo p){

    }

};

What should my private datamember look like and how do I add p to it? And do I need a pointer for some reason?

2
  • 1
    You should look into the STL; there are a variety of container types in there (vector is the one that comes to mind here, but there may be others that suit your problem better). Commented Mar 11, 2012 at 23:40
  • you may want to pay attention to heap space allocation. if the Album object is going to be big, maybe it is better to allocate with new. Commented Mar 12, 2012 at 18:16

4 Answers 4

2

The functionality you look for already exits in the stl collection classes and and with out knowing you application it would be had to tell you weather you needed a pointer or not.

The basic layout of you underlying container could be something like this.

class Album{    

public:
    void addPhoto(Photo p){
         Photos.push_back(p); 
    }
private:
    std::vector<Photo> Photos; 

};
Sign up to request clarification or add additional context in comments.

7 Comments

Just curious, where did you originally learn to put an underscore for class members (i.e. _Photos), I know doing it after like (Photos_) is popular too which I believe was popularized by "C++ Coding Standards" book).
I like the answer, but you shouldn't be using _Photo. See this for a reasons why: stackoverflow.com/questions/228783/… Happy to see it as Photo_ though.
its the current coding standard where I work just habit. I like it because of intelisense. At other jobs we have done m_ _ or absolutely no notation at all. It feels more popular in MS shops where hungarian notation dies hard.
Underscore-captial names are reserved and must not be used by user code. As such, your code exhibits undefined behaviour.
Wow did not know that at all nor have I ever run into it
|
2

You should use an std::vector.

Comments

0

You could use the built in std::vector class that behaves very similarly to the ArrayList. (edit... looks like someone beat me to it)

Comments

0

@fontanini gave you a good answer, you should use vector if you need a dynamic array of objects.

But maybe you don't need a class to begin with. Not everything in C++ needs to be encapsulated in a class, unless you really need it.

Think about your data structure and what are the requirements. You might want to learn more about standard C++ library and the STL to familiarize yourself with other containers and their capabilities, limitations and objectives:

There are excellent video lectures on STL "Introduction to STL with Stephan T Lavavej"

Comments

Your Answer

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