Friday, June 14, 2019

virtual function / pure virtual function example

#include <iostream>
using namespace std;

class Animal
{
public:
//        virtual void eat() { std::cout << "I'm eating generic food." << std::endl; }
    virtual void eat() =0; // pure virtual function ends with =0, this class cant be instantiate

    // turn the following virtual modifier on/off to see what happens
    //virtual
    std::string Says()
    {
        return "make virtual ?";
    }
};

class Cat : public Animal
{
public:
    void eat() override
    {
        std::cout << "I'm eating a rat." << std::endl;
    }
    void hi()
    {
        std::cout << "hiiii" << std::endl;
    }
    std::string Says()
    {
        return "Cat Woof";
    }
};

void func(Animal *xyz)
{
    xyz->eat();
//    xyz->hi();
}

int main()
{
//    base *p;
//    derived obj1;
//    p = &obj1;
//
    Animal *animal = new Animal;
    Cat *cat = new Cat;

//    animal->eat(); // Outputs: "I'm eating generic food."
//    cat->eat();    // Outputs: "I'm eating a rat."

//    func(animal); // Outputs: "I'm eating generic food."
    func(cat);    // Outputs: "I'm eating generic food."

    //////////////////////////
    Cat* c = new Cat();
    Animal* a = c;       // refer to Dog instance with Animal pointer

    cout << c->Says() << std::endl ;   // always Woof
    cout << a->Says() << std::endl;   // Woof or ?, depends on virtual

    return 0;
}


///////////////////////////////////////////
https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c

Why virtual function


, assume for example a situation in which you had a function in your program that used the methods from each of the derived classes respectively(getMonthBenefit()):
double totalMonthBenefit = 0;    
std::vector<CentralShop*> mainShop = { &shop1, &shop2, &shop3, &shop4, &shop5, &shop6};
for(CentralShop* x : mainShop){
     totalMonthBenefit += x -> getMonthBenefit();
}
Now, try to re-write this, without any headaches!
double totalMonthBenefit=0;
Shop1* branch1 = &shop1;
Shop2* branch2 = &shop2;
Shop3* branch3 = &shop3;
Shop4* branch4 = &shop4;
Shop5* branch5 = &shop5;
Shop6* branch6 = &shop6;
totalMonthBenefit += branch1 -> getMonthBenefit();
totalMonthBenefit += branch2 -> getMonthBenefit();
totalMonthBenefit += branch3 -> getMonthBenefit();
totalMonthBenefit += branch4 -> getMonthBenefit();
totalMonthBenefit += branch5 -> getMonthBenefit();
totalMonthBenefit += branch6 -> getMonthBenefit();
And actually, this might be yet a contrived example either!