The difference in using virtual and not using virtual

Possible duplicate:
Override vs Virtual

In C ++, regardless of whether you want to use virtual or not, you can still override the function of the base class. The following compiles just fine ...

class Enemy 
{
public:
    void SelectAnimation();
    void RunAI();
    void Interact()
    {
        cout<<"Hi I am a regular Enemy";
    }

private:
    int m_iHitPoints;
};

class Boss : public Enemy
{
public:
    void Interact()
    {
        cout<<"Hi I am a evil Boss";
    }
};

So my question is what is the difference in using or not using a virtual function. And what is the disadvantage.

+3
source share
4 answers

If you have a code:

Enemy * p = new Boss;
p->Interact();

Interact , Enemy Interact. , , , . , , , (, ), . , .

+18

Enemy::Interact() virtual, Enemy::Interact() - Interact().

:

Boss boss;
Enemy* bossEnemy = &boss;

boss.Interact();       // calls Boss::Interact()
bossEnemy->Interact(); // calls Enemy::Interact()

Enemy::Interact() virtual, Boss::Interact() , .

, , . , , , .

+6

-, : 50% . ( ) , , .

.

+3

. . .:)

virtual ++ -. , ++ . virtual, . , .

, ? , , , . , , "" , ? , , .

, , , , . , virtual, OO.

: -, . ++ . , .

-, . , -, . . , . , ? , , . , ? . , . , . , , , .

Thirdly, it is easily measurable, and it’s great because you don’t need to take our word for it. You can easily correlate the difference with your compiler in your target architecture to make sure that there really is no difference in performance .

0
source

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


All Articles