2

Finding the appropriate title to this question is a little difficult for me, but here is my situation. Say I have a base class and a derived class, can I pass a function that takes a parameter of type *base a type of instead *derived

class base
{
protected:
    float M_OutputValue;
    float M_InputValue;
public:
    virtual void CalculateOutput() = 0;
        /* more functions */
};

class derived: public base
{
public:
    void CalculateOutput(){ /*stuff*/};
    /* more functions */
};

And here is a function that would take the base class as an input.


void CalculateAllOutputs(base* basearray, int NumberofElements)
{
    int temp = 0;
    while(temp < NumberOfElements)
    {
         basearray[temp]->CalculateOutput();
         temp++;
    }
};

I'm and wondering if I can pass this function a pointer to an array of derived objects. From what I understand about casting pointer from derived to base, it is implicit and there isn't much to worry about (I looked at this question for answers). My concern is that because the derived class has more members, it takes up more bytes. That would cause the members in the array to be farther apart, so when iterating through it, a larger offset would need to be added to the memory address to get to the next element. I'm wondering if the compiler takes care of these problems so that the function I'm passing the array to knows how to access the members of the derived array. I could also solve my problem with templates of there is no solution here, but I'm trying to get better at polymorphism.

Thanks.

2 Answers 2

2

You are right. Stay away from arrays, and preferably use

std::vector<std::unique_ptr<base>>

or if you don't have a C++0x-ready compiler (if this is the case, then consider upgrading), you can use

boost::ptr_vector<base>

Both are vectors of pointers which automatically clean up the pointed to objects. Avoid raw pointers, and as you point out, plain arrays simply suck.

Example of use:

void calculate_outputs(const std::vector<std::unique_ptr<base>>& b)
{
    std::for_each(b.begin(), b.end(), [](const std::unique_ptr<base>& x)
    {
        x->CalculateOutput();
    });
}
5
  • I do like vectors, it's just that they save a little extra space after reallocation when they grow so they constantly don't have to be reallocated. I have a lot of small objects and don't want the extra space to be used up. Then again, if it was a vector of pointers it would be a good idea, so I will see. Btw, if I'm not constantly resizing, can I make the vector not reserve a little extra for future growth? Aug 10, 2011 at 21:54
  • @JAKE: it is a vector of pointers which automatically delete themselves when the vector disappears. Also, you cannot go wrong when copying the vectors. Don't bother with extra space. If you really must, you can use vector::reserve if you know beforehand how much space you'll exactly need: the vector won't allocate extra space. Aug 10, 2011 at 21:59
  • Unless it changed since I last looked (which was a long time ago) reserve will alllocate at least the memory requested but may allocate more, so it doesn't address the OP's concern. You can use capacity to see how much space is allocated, but I don't think there is a portable way to request an exact amount of space.
    – john
    Aug 10, 2011 at 22:13
  • @john: most (virtually all) implementations will fulfill the request within a factor two. Also, we are dealing with containers of pointers, so the overhead will be negligible with respect to the pointed-to objects. I'd never give up the convenience of vector for this (I'd even rather buy 2Gb extra RAM for under $20). Aug 10, 2011 at 22:15
  • @Alexandre: My biggest problem is that VC++ Express 2010 only supports 32 bit compilation. If I had a 64bit, that would help as I could overcome the 2GB limit (or 3GB with switch) as I have 6GB of ram and I'm dealing with arrays of floats for weights for ANNs. Maybe one day, when I save enough, I'll get professional ;) Aug 13, 2011 at 16:46
2

Your concern is exactly right. Passing an array of derived would not work. If you want an array (or a vector) of polymorphic objects you are going to have to create an array of pointers. This means your function would look like this

void CalculateAllOutputs(base** basearray, int NumberofElements)
{
    int temp = 0;
    while(temp < NumberOfElements)
    {
         basearray[temp]->CalculateOutput();
         temp++;
    }
}

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.