Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of class objs

Tags:

c++

Consider following class

class test
{
public:
test(int x){ cout<< "test \n"; }

};

Now I want to create array of 50 objects of class test . I cannot change class test.

Objects can be created on heap or stack.

Creating objs on stack is not possible in this case since we dont have default constructor in class

test objs(1)[50]; /// Error...

Now we may think of creating objs on heap like this..

test ** objs = NULL;
objs = (test **) malloc( 50 * sizeof (test *));
for (int i =0; i<50 ; ++ i)
{
   objs[i] = new test(1);
}

I dont want to use malloc .Is there any other way??

If you guys can think of some more solutions , please post them...

like image 796
anand Avatar asked Dec 06 '22 07:12

anand


2 Answers

You cannot create an array of objects, as in Foo foo [N], without a default constructor. It's part of the language spec.

Either do:

test * objs [50];
for() objs[i] = new test(1).

You don't need malloc(). You can just declare an array of pointers.

c++decl> explain int * objs [50]
declare objs as array 50 of pointer to int

But you probably ought to have some sort of automatic RAII-type destruction attached.


OR subclass test publicly:

class TempTest : public test
{
public:
  TempTest() : test(1) {}
  TempTest(int x) : test(x) {}
  TempTest(const     test & theTest ) : test(theTest) {}
  TempTest(const TempTest & theTest ) : test(theTest) {}
  test & operator=( const     test & theTest ) { return test::operator=(theTest); }
  test & operator=( const TempTest & theTest ) { return test::operator=(theTest); }
  virtual ~TempTest() {}
};

and then:

TempTest  array[50];

You can treat every TempTest object as a test object.

Note: operator=() & copy constructor are not inherited, so respecify as necessary.

like image 62
Mr.Ree Avatar answered Dec 07 '22 21:12

Mr.Ree


Why do you need array?

std::vector<test*> v(50);

Or as @j_random_hacker suggested in the comments:

std::vector<test> v(50, test(1));

An example:

/** g++ -Wall -o vector_test *.cpp && vector_test */
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

struct Test {
  int value;
  Test(int x) : value(x) 
  {
    std::cout << "Test(" << value << ")" << " ";
  }
  operator int() const
  {
    std::cout << "int(" << value << ")" << " ";
    return value;
  }
};

int main()
{
  using namespace std;

  vector<Test> v(5, Test(1));

  cout << endl;
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
  cout << endl;

  v[1] = 2;
  v[2].value = 3;

  cout << endl;
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
  cout << endl;

  return 0;
}

Output:

Test(1) 
int(1) 1 int(1) 1 int(1) 1 int(1) 1 int(1) 1 
Test(2) 
int(1) 1 int(2) 2 int(3) 3 int(1) 1 int(1) 1 
like image 29
jfs Avatar answered Dec 07 '22 21:12

jfs