• Advertisement
Sign in to follow this  

I want to make a function which creates ....

This topic is 4681 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to make a function which creates an array of objects. i want the number of objects to be an arguement of the function. example:
int myFunc(int number)
{
   for(i = 0; i<number; i++)
   {
       Line joseph = new Line[number];
   }
return 0;
}



Line is a class. but that doesn't work. how would I go about doing this?

Share this post


Link to post
Share on other sites
Advertisement
It works, but only inside of your function ;-) However, your way of creating an array seems a bit odd to me.. Why are you doing it inside of a loop? ;-)

Line *joseph;

***

int myFunc(int number)
{
joseph = new Line[number];
return 0;
}
// you don't need to recieve a value from this function so you could use this:
void myFunc(int number)
{
joseph = new Line[number];
}






You only created "joseph" as a local variable - it exist only during function executing time... That's why I used "joseph" as a global variable - it exist as long as your program runs.

EDIT: You need to use a pointer if you are dynamicaly allocating an array.

Share this post


Link to post
Share on other sites
In addition to what RiBi has said, the Line class must contain a default constructor so you can do this. Your class should look something like this:

... H File ...
class Line
{
private:
... Other stuff ...
public:
Line(); // Default ctor
... Other stuff ...
};

... CPP File ...
Line::Line()
{
// Do whatever here
}

Share this post


Link to post
Share on other sites
well this function is actually a member function of a class.
later if I want to access onw of the lines in that array can I just use

object.joseph[1].draw();

draw is a function of the Line class and joseph[] is now a member of the top class


or is there more to it than that?

Share this post


Link to post
Share on other sites
Quote:
Original post by donjonson
but that doesn't work. how would I go about doing this?


Assuming that is C++ code for a moment you need to use pointers to create C-style dynamic arrays e.g.


void foo(int size) {
Line* l = new Line[size];
....
delete[] l;
}


Now you know that, it's time learn not to use C style dynamic arrays in C++, use C++ dynamic arrays i.e. std::vector:


#include <vector>

void foo(int size) {

std::vector<Line> v(size);
.....
}


or:


#include <vector>

void foo() {

std::vector<Line> v;

v.push_back(Line());
.....
}


or best of all:


#include <vector>

void foo(int size) {

std::vector<Line> v;

v.reserve(size); // pre-allocates memory only

v.push_back(Line());
.....
}


You can read more about the standard library vector here and here also.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement