jeudi 27 octobre 2016

Virtual Functions

// virtual members
#include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
     int area ()
      { return 0; }
    void set2_values (int,int);
    virtual bool incompressible() const = 0;
};
bool Polygon::incompressible() const {
    return 1;
}
void Polygon::set2_values (int x, int y) {
  width = x;
  height = y;
}

class Rectangle: public Polygon {
  public:
    int area ()
      { return width * height; }
    virtual bool incompressible() const {
        return 1;
    }
};

class Triangle: public Polygon {
  public:
    int area ()
      { return (width * height / 2); }
    bool incompressible() const {
        return 0;
    }
};

int main () {
  Rectangle rect;
  Triangle trgl;
  Polygon poly;
  Polygon * ppoly1 = &rect;
  Polygon * ppoly2 = &trgl;
  Polygon * ppoly3 = &poly;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  ppoly3->set_values (4,5);
  ppoly3->set2_values (4,5);
  //ppoly3->incompressible();
  cout << ppoly1->area() << '\n';
  cout << ppoly3->incompressible() << '\n';
  cout << ppoly2->area() << '\n';
  cout << ppoly3->area() << '\n';
  return 0;
}

Error: In function 'int main()': 45:11: error: cannot declare variable 'poly' to be of abstract type 'Polygon' 5:7: note: because the following virtual functions are pure within 'Polygon': 16:6: note: virtual bool Polygon::incompressible() const Can anyone explain why I am facing this issue.?

Aucun commentaire:

Enregistrer un commentaire