Subclass not overriding virtual method

I'm new to the arduino language but I'm a Java and C programmer (not C++).

I want two classes, one a base class and the other a subclass derived from the base class, so I can have an array of mixed instances of these two classes, declared as being of base class.

When I run the following test program it gives the same result whether I type 0 or 1 as the command. That is, the subclass is not overriding the virtual method in the base class.

class B
{
  public:
  B(){}
    
  B(int hello, int there)
  {
    // whatever
  }
  
  virtual void printClass()
  {
    Serial.println("B");
  }
};

class D: public B
{
  public:
  D(int other)
  {
    // whatever else
  }
  
  virtual void printClass()
  {
    Serial.println("D");
  }
};

B b[2]; // array to hold a mix of instances of B and D

void setup()
{
  // one instance of B and one of D
  b[0] = B(0,30);
  b[1] = D(1);
  
  Serial.begin(57600);
  Serial.println("\nStarted");
}

void loop()
{
  char command;
  
  // check if data has been sent from the computer
  if (Serial.available())
  {
    // read the most recent character
    command = Serial.read();
    
    // call printClass on instance of B if command is 0
    // call printClass on instance of D if command is 1
    Serial.print("'");
    Serial.print(command);
    Serial.print("'=");
    if (command == '0')
      b[0].printClass();
    else if (command == '1')
      b[1].printClass();
  }
}
Started
'0'=B
'1'=B

What do I have to do to make it work?

Thanks.
Paul

I think the problem is the statement:

b[1]=D(1);

You are indeed creating a D() instance, but then copying it into a B object. The D() identity is lost during the copy (and I bet the compiler is putting out some nasty warnings too).

Try it more like this:

B *b[2];

void setup()
{
  b[0] = new B(0,30);
  b[1] = new D(1);
...
void loop()
...
  if (command == '0') b[0]->printClass();
  else if (command == '1') b[1]->printClass();
...

Thanks for helping.

When I try your changes, the arduino compiler complains with:

o: In function `setup':
undefined reference to `operator new(unsigned int)'

However, when searching for an answer last night I found a reference to
http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=59453
which suggests adding the following code. This seems to work:

#include <stdlib.h>

void * operator new(size_t size);
void operator delete(void * ptr); 

void * operator new(size_t size)
{
  return malloc(size);
}

void operator delete(void * ptr)
{
  free(ptr);
}

With the Arduino - 0015 development environment I seem not to require the other additions suggested.

Again, thanks for your help.
Paul