Why does the derived class not work in the array? (C ++)

I created a class called vir with the move function:

class vir
{
public:
     vir(int a,int b,char s){x=a;y=b;sym=s;}
     void move(){}
};

(It is derived from a class with variables int x, int y and char sym) I got a class from this called subvir:

class subvir:public vir
{
public:
     subvir(int a,int b,char s){x=a;y=b;sym=s;}
     void move();
};
subvir::move()
{
     x++;
     return;
}

And then I created a vir array and put a subvir in it

subvir sv1(0,0,'Q');
vir vir_RA[1]={sv1};

But when I try to use sv1.move ():

vir_RA [0] .move ();

It uses the vir move ({}) rather than the sub-move move ({x ++}). I tried to make sv1 vir and vir_RA a vir, and it works, and it also works when I make them both subvir, but I need them to be different. I tried to make vir :: move () pure virtual, but then I get an error message justifying the array. Does anyone know how I can make move () work when I use it from an array?

+3
6

, . vir * [] vir []

+5

virtual, , , - , . , / . :

class vir
{
public:
     vir(int a,int b,char s){x=a;y=b;sym=s;}
     virtual void move(){}
};

move . move . :

void subvir::move()
{
     x++;
     return;
}

, ( ), . , vir :

vir* v[ 2 ] = { new subvir(0, 0, 'Q'), new subvir(10, -10, 'P') };

f ++ FAQ Lite:

+8

. vir, , , vir:: move. move() .

. . sizeof vir!= Sizeof subvir, . . , .

+5

, , , , , , . N * size (base_type). (base_type) . , , .

+2

.

. - . virs . vir , vir. subvir , vir, , vir . vir subvir - , vir, subvir, vir. , , vir , . vtable vir vtable, subvir. , , subvir , vir.

- . ( move()) , move() vir ( virs). (, , , - , , .) subvir, , subvir:: move(), move() ) virtual in vir.

, ( sv1, , ).

+1

Source: https://habr.com/ru/post/1707539/


All Articles