Dhiego Magalhães
Dhiego Magalhães

Reputation: 70

C++ new object every time function is called?

What I want is a function that makes a new different instance every time i call it (with a different name...)

Just like this:

void person::new_person(){
  person *(id+index) = new person(name_temp, age_temp, quote_temp);
}

But it doesn't work... I don't know how should i do that... (index is add by one every time i make a new instance). And i realized every time i make a pointer and just add spaces on it, like that:

int*p;
*(p+1) = 5;

It compiles, but freezes while running(I supose its getting memmory thats not allowed), so that "person *(id+index)" may not work too. What do you think?

Upvotes: 0

Views: 1895

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

“What I want is a function that makes a new different instance every time i call it (with a different name...) ”

That’s known as a constructor, and it's a special kind of member function, with the same name as the class. It doesn’t have a function result type, not even void. It can go like this:

class Person
{
private:
    string name_;

public:
    Person( string name )
        : name_( name )
    {}
};

Then there are a variety of ways to call it, depending on where you want the new instance stored. E.g.,

int main()
{
    Person a( "A" );    // Local variable
    Person( "B" );      // A temporary, it's already destroyed... ;-)
    vector< Person > v;
    v.emplace_back( "C" );    // As a new item at the end of vector.
}

Plus some, but I guess the three ways above are the most relevant to a complete beginner.

Note that with the vector, every time you push_back or emplace_back you’re creating a new last item, with a new index. Call the size method to find out how many items you currently have in a vector. Check the documentation for more information.

By the way, you should really get yourself a textbook.

Upvotes: 3

StackedCrooked
StackedCrooked

Reputation: 35485

You mean something like this?

#include <string>

person make_person()
{
    static unsigned i = 0;
    return person(std::to_string(i++));
}

Upvotes: 5

Robᵩ
Robᵩ

Reputation: 168626

Try keeping your persons in a standard container:

std::vector<person> people;
void person::new_person(std::string name, int age, std::string quote){
      people.push_back(person(name, age, quote));
}

Upvotes: 8

Related Questions