czwartek, 23 marca 2017

[C++]Virtual methods

#include <iostream>
const float pi = 3.14159;

class Shape
{
public:
    virtual float getArea()//"virtual" couses, compilator
    {                    //have to find out, on which object
        return -1.0;     //pointer points (base or derivative)
    }
};

class Square: public Shape
{
public:
    Square(const float side): a(side){}
    void pureVirtualMethod(){}
    float getArea()
    {
        return a * a;
    }

private:
    float a;
};

int main ()
{
    Shape *shape;
    Square square(3);
    shape = &square;
    std::cout<<square.getArea()<<std::endl;
    /*if in base class the getArea() method wasn't mark as virtual
    that following line will call method from base class(not derivative)*/
    std::cout<<shape->getArea()<<std::endl;
}

Brak komentarzy:

Prześlij komentarz