You are not logged in.

#1 2010-03-02 01:19:55

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

[c++] define a class as an array

I've defined a class which will 99 times out of 100 be used as a collection of objects. I'd like to be able to extend the class to be a collection of its own, rather than having to define the array of objects on the application level. My goal is to be able to define a search method at the class implementation level as well. Research thus far has told me that inheriting from vector, or anything from STL in general is a bad idea because they don't provide proper deconstructors and will leak.

Is there a way to inherit an array-type construct into my class that isn't going to cause problems down the line? Or, should I suck it up and just define the array and search algorithm at the application level?

Any pointers would be much appreciated.

Offline

#2 2010-03-02 01:25:32

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,404
Website

Re: [c++] define a class as an array

You could make a class with a std::vector of your objects as a member variable.

Offline

#3 2010-03-02 01:35:26

testube_babies
Member
From: 127.0.0.1
Registered: 2007-06-26
Posts: 115

Re: [c++] define a class as an array

falconindy wrote:

Any pointers would be much appreciated.

0x65af37e8
0x49e8b2cc
0x87a7f220

Offline

#4 2010-03-02 01:42:33

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: [c++] define a class as an array

Allan wrote:

You could make a class with a std::vector of your objects as a member variable.

Now there's a ludicrously simple idea that I like.

testube_babies wrote:

0x65af37e8
0x49e8b2cc
0x87a7f220

I knew that was coming. lol.

Offline

#5 2010-03-03 12:40:28

Sadface
Member
From: Germany
Registered: 2009-12-09
Posts: 47

Re: [c++] define a class as an array

How about overloading "operator[]"?

#include <iostream>
using namespace std;

class MyClass {
  int a[3];

public:
  MyClass(int i, int j, int k) {

    a[0] = i;

    a[1] = j;

    a[2] = k;
  }
  int operator[](int i) { 

     return a[i]; 

  }
};

int main()
{
  MyClass object(1, 2, 3);

  cout << object[1];

  return

Offline

#6 2010-03-03 12:55:18

sr
Member
Registered: 2009-10-12
Posts: 51

Re: [c++] define a class as an array

Perhaps the more general method of making this work is to define the relevant iterator_traits <> class (and the iterators too, of course). IIRC, this should make it possible to use the standard library algorithms directly on your container type.

Offline

Board footer

Powered by FluxBB