1

i'm new to c++ programming, with previous knowledge about AS3 programming. My problem is that i cannot figure out how to insert a new object form a class into an array.

Basically what i'm trying to do is:

ClassName classArray[];
classArray[n]=new ClassName("Tekst");

Here is my code (written using visual studios 2012 C++):

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

//a class holding user data
class User
{
public:
    string name;
    User(string nameInn)
    {
        //when the user is created it should get information about its name.
        name=nameInn;
    }
};

//array with all users
User userArr[];
int userArrLength=0; //the length of that array (dont know how to find the length of arays holding classes)

int main()
{
    //the user writes down the name of all users.
    cout << "Write user name. \n Write \"fin\" til finish\n";
    bool hasFinished=false;
    //asks you for a new user until you write fin
    while(hasFinished==false)
    {
        string inn;
        cin >> inn;
        if(inn=="fin") hasFinished=true;
        //here im trying to make a new user inn a new spot in the userArr.
        else userArr[(userArrLength+=1)+1]=new User(inn);
    }

    return 0;
}

Is my formatting just wrong, if so how do i format it? Or have i misunderstood something essential about classes in C++?

7
  • You're definitely getting errors in this program. Can you list them all down for us? Commented Jun 9, 2013 at 12:32
  • 2
    I think you must erase java from your head and start with some C++ teaching book. Similar looking things behave quite differently here Commented Jun 9, 2013 at 12:34
  • First thing that comes to mind when looking at your first example is: new X() returns a pointer to X so you need an array of pointers to X instead of an array of X. Commented Jun 9, 2013 at 12:55
  • @confusopoly maybe they don't need new at all? Commented Jun 9, 2013 at 12:57
  • @juanchopanza Possibly, but then you get an array of default-constructed objects and calls to the assignment operator of the class for every object you put in the array. And that is something I usually prefer to avoid unless I know that the class implements it properly. Edit: nvm, the class only contains one std::string member so it shouldn't cause any problems. Commented Jun 9, 2013 at 13:11

4 Answers 4

2

std::vector is a data structure implementing a dynamically sized array that can grow in size as needed. You can use an std::vector<User> instead of your own array:

#include <vector>

...

  std::vector<User> v;

  // perhaps in a loop
  string inn;
  cin >> inn;
  v.push_back(User(inn));
Sign up to request clarification or add additional context in comments.

Comments

1

In C++, arrays are of a static size. In addition, new creates a pointer which means you're additionally using the wrong datatype for your array.

The suggested way to go around this would be to use a vector, instead:

// At the top
#include <vector>

// Instead of that array
std::vector<User> userVector;

// Inside of the loop
userVector.push_back(User(inn));

std::vector is essentially a dynamic array.

There is still, however, something to consider: When space is allocated for the vector, all of its members are initialised with the default constructor (ie. the one that can be called without parameters).

If your User class has no default constructor If your cl, you will have to insert pointers to User (std::vector<User * > userVector and userVector.push_back(new User(inn))) instead, and manually remove the pointers with delete afterwards. (See comment below)

1 Comment

The last two paragraphs are wrong. std::vector does not require your class to have a default constructor. Raw memory is allocated, and then objects are constructed in-place, with the copy(or move) constructor. The only time you need a default constructor is if you call the single argument version of resize.
1

You can't change the length of an array once it's been created.

Comments

0

If you don't know the size of the array, then you should not be using static arrays. You should be using dynamic arrays. Something like this:

#include <vector>

std::vector<User> userArr;

Here userArr will be a vector which has a dynamic size. Then you can change your while loop to do this instead:

std::vector<User> arr;

for (std::string in; std::cin >> in && in != "fin";)
{
    arr.push_back( User(in) );
}

2 Comments

std::string in; std::cin >> in && in != "fin"; What does that mean? Also do you need to use the std:: in those cases?
@TubeOfJokes All basic_istream objects have a boolean operator that when invoked, returns whether the stream has any errors. The && operator tries to convert it to a boolean. That line is basically saying "As long as the user enters in valid input for in and as long as in doesn't equal "fin" after the input, do this...".

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.