Passing a Derived class reference to a function using a base class pointer

I'm sure this is OOP 101 (maybe 102?), But I am having trouble understanding how to do this.

I am trying to use one function in my project to get different results based on which object is passed to it. From what I read today, I think I have the answer, but I hope that someone here can lift me up a bit.

//Base Class "A"
class A
{
    virtual void DoThis() = 0; //derived classes have their own version
};

//Derived Class "B"
class B : public A
{
    void DoThis() //Meant to perform differently based on which
                  //derived class it comes from
};

void DoStuff(A *ref) //in game function that calls the DoThis function of
{ref->DoThis();}     //which even object is passed to it.
                     //Should be a reference to the base class

int main()
{
    B b;

    DoStuff(&b);     //passing a reference to a derived class to call
                     //b DoThis function
}

Moreover, if I have several base-based classes, can I pass any Derived class to functions DoStuff(A *ref)and use virtual files from the base?

Am I doing it right or am I from here without reason?

0
source share
1

, IDEOne, ( ), ,

#include <iostream>
using namespace std;

class Character 
{
public:
    virtual void DrawCard() = 0;    
};

class Player: public Character
{
public:
    void DrawCard(){cout<<"Hello"<<endl;}
};

class Enemy: public Character
{
public:
    void DrawCard(){cout<<"World"<<endl;}
};

void Print(Character *ref){
    ref->DrawCard();
}

int main() {

    Player player;
    Enemy enemy;

    Print(&player);

    return 0;
}

Print(&player) Print(&enemy) DrawCard(), , . . , .

0

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


All Articles