can pointers of a mother class type point to its daughter class ?if yes,why? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

can pointers of a mother class type point to its daughter class ?if yes,why?

https://code.sololearn.com/cOpB3W8KSDn5/?ref=app saw *Enemy e1=&Ninja; but they two were just of different classes,was this designed?what if I make an "e1++;" action?will e1 jump a sizeof(Enemy) size or a sizeof(Ninja) size or just go wrong?please help!!

6th May 2018, 3:20 PM
ŠŁĘŠÂŤ
ŠŁĘŠÂŤ - avatar
3 Antworten
+ 9
hello! 1st) the tag abstract is wrong, sorry.. An abstract class have a pure virtual member function : virtual void example()=0; and cannot be instantiated. An abstract class is meant to be a base class only. The topic here is polymorphism and you can find information inside the c++ course, if you need help feel free to ask! 2nd) pointer arithmetic on polymorphic is undefined behaviour, absolutely avoid it! But you can use an array of ponters! like this: Ninja n; Monster m; ... Enemy* enemies[ amount ] ; enemies[ 0 ] = &n; enemies[ 1 ] = &m; .... void nextTurn() { for ( int i=0 ; i <amount ; i++){ enemies [ i ]->attack(); } } hope it helps!
6th May 2018, 10:34 PM
AZTECCO
AZTECCO - avatar
+ 1
In your case it doesn't matter because the classes are the same size. But in general 'ptr++' will jump by sizeof(Enemy), which can get you into trouble if Ninja is bigger, yes!
6th May 2018, 5:11 PM
Schindlabua
Schindlabua - avatar
+ 1
thanks guys ! I'm so much grateful ..
7th May 2018, 7:07 AM
ŠŁĘŠÂŤ
ŠŁĘŠÂŤ - avatar