S
S
Sinus_3142020-06-30 10:33:29
C++ / C#
Sinus_314, 2020-06-30 10:33:29

How to call an overridden function on a child object that is in the parent array?

There is a Moved class:

class Moved{
  public:
    virtual int getType();
    virtual int getBS() ;
};

There are two child classes:
class Car : public Moved{
  public:
    int getBS() override;
    int getType() override;
};
class Walker : public Moved{
  public:
    int getBS() override;
    int getType() override;
};


They are initialized:
int Moved::getBS() {
  return -1;
}
int Moved::getType() {
  return -1;
}

int Car::getBS() {
  return 3;
}

int Walker::getBS() {
  return 1;
}
int Car::getType() {
  return 0;
}
int Walker::getType() {
  return 1;
}


But when used, the parent function is called:
void Printer::addM(Moved obj) {
  Moved* tmp = new Moved[mSize];
  for (int i = 0; i < mSize; i++) tmp[i] = objs[i];
  objs = new Moved[++mSize];
  for (int i = 0; i < mSize - 1; i++)
    objs[i] = tmp[i];
  
  objs[mSize - 1] = obj;
  Car mytmp; // для теста
  cout << mytmp.getType() << endl; // для теста
  cout << objs[mSize-1].getType() << endl; 
  Sleep(100);
}


Car M;
  Car M1;
  Car M2;
  Car M3;
  Car M4;
  Walker W;
  Walker W1;
  Walker W2;
  P.addM(M);
  P.addM(M1);
  P.addM(M2);
  P.addM(W);
  P.addM(W1);
  P.addM(W2);

5efaea298eff7353217206.png
I see two options: either I'm a fool, or I'm a fool - I can't choose, help me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2020-06-30
@Sinus_314

Reformatted the code for myself. I can't take Egyptian brackets.

void Printer::addM(Moved obj) 
{
  Moved* tmp = new Moved[mSize];
  for (int i = 0; i < mSize; i++) 
  {
      tmp[i] = objs[i];
  }
  objs = new Moved[++mSize];
  for (int i = 0; i < mSize - 1; i++)
  {
    objs[i] = tmp[i];
  }
  objs[mSize - 1] = obj; 
  Car mytmp; // для теста
  cout << mytmp.getType() << endl; // для теста
  cout << objs[mSize-1].getType() << endl; 
  Sleep(100);
}

You have two problems. Firstly, you reinvented std::vector for some reason, so you have to write about 5 times more code than you need.
Secondly, you need to store not Moved objects, but pointers to them, and then your homological class hierarchy will work.
As I said above, addM doesn't work the way you'd expect. When you call it, you create a Moved based on Car or Walker, which eliminates polymorphism.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question