-2

I would like to extend a base class which has a virtual function that takes a pointer to an array of a type. The derived class is more complex and could take advantage of multiple pointers to an array of that type.

derived and other show different solutions to deals with that problem, but I dislike both of them. Is there anything I could do instead?

struct base {
    virtual void set(int* p, std::size_t n) { }
};

struct derived : base
{
    virtual void set(int* p, std::size_t n)
    {
        int** pp = new int*[1]; // must be deleted before destruction
        pp[0] = p;
        set(1, pp, n);
    }

    void set(std::size_t count, int* const* pp, std::size_t n)
    {
    }
};

struct other : base
{
    virtual void set(int* p, std::size_t n)
    {
        m_helper[0] = p;
        set(1, m_helper, n);
    }

    void set(std::size_t count, int* const* pp, std::size_t n)
    {
    }

private:
    int* m_helper[1];
};
1
  • 4
    I really understand neither your question nor your examples. Can you explain what your actual goal is? Jun 25, 2011 at 15:09

3 Answers 3

2

Theoretically, if you don't want to save the pointer itself, this should do:

virtual void set(int* p, std::size_t n)
{
    set(1, &p, n);
}

void set(std::size_t count, int* const* pp, std::size_t n)
{
}
1

The code doesn't say anything about the goal which you want to achieve, as every function is almost empty. So I cannot suggest anything better than to use the following:

  • Use std::vector<int> where you want to use int*
  • Use std::vector<std::vector<int> > where you want to use int**
0

You could use variable argument lists:

void set(std::size_t count, std::size_t n, ...) {
  va_list v;
  va_start(v, n);

  for (int i = 0; i < count; i++)
  {
    int* value = va_arg(vl, int*);
    // ...
  }

  va_end(v);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.