array of derived classes problems

Hi,

I'm trying to learn how to have an array of derived classes.
The code below shows a simplified version of the problem I am experiencing.

As you can see, in main() I instantiate a base class and a deriveA class object.
If I call their member functions printMe() they print out what I would expect.

However, if in the holder class which creates an array. With the first item in the array being a base class and the second being a deriveA class. Then when I call holder.printArray() it results in both items in the array printing the base class method of printMe().

I'm confused as to why this is happening, but since this is the first time I have ever attempted this and my knowledge of C++ is rusty to say the least. I'm guessing it's something I am doing wrong.
If some kind person could point out the errors in my code I'd appreciate it.

Many thanks

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdlib.h>
#include <iostream>



class base
{
    public:
        base(){};
        void printMe(){ std::cout << "im base class" << std::endl;};
};

class deriveA:public base
{
    public:
        deriveA(){};
        void printMe(){ std::cout << "im deriveA class" << std::endl;};
};


class holder
{
    public:
        holder(){
            arraySize = 2;
            testArray = new base*[arraySize];
            testArray[0] = new base();
            testArray[1] = new deriveA();
            };
        void printArray(){
            int i;
            for( i=0; i<arraySize; i++)
            {
                testArray[i]->printMe();
            }

            }
    private:
        base **testArray;
        int arraySize;
};

int main(int argc, char **argv)
{
    base b;
    b.printMe();

    deriveA da;
    da.printMe();

    holder h;
    h.printArray();

    return 1;
}
If you want polymorphic behaviour you need to mark the function as virtual in the base class.
1
2
3
4
5
6
class base
{
    public:
        base(){};
        virtual void printMe(){ std::cout << "im base class" << std::endl;};
};
ahhh thank you.
So do you only need to mark the functions as virtual in the base class ?
If the function is virtual in the base class it is automatically virtual in the derived classes so it doesn't matter if you use virtual in the derived class or not.
Thanks Peter, that was just what I was looking for.
Cheers
Topic archived. No new replies allowed.