Could you please help me out on working with abstract classes by sending me a simple example of it.
Please also write the main.cpp
An example of Abstract Class with Pure Virtual function?
Here's an example, using an abstract class Shape with a pure virtual function getArea, and two subclasses, Circle and Rectangle. Hope it helps.
-------------------
#include %26lt;iostream%26gt;
using namespace std;
class Shape {
public:
// getArea is a pure virtual method: no implementation
// is provided in the base class, which makes the base
// class abstract
virtual double getArea() = 0;
};
class Rectangle : public Shape {
public:
Rectangle(double h, double w);
virtual double getArea();
private:
double _h, _w;
};
class Circle : public Shape {
public:
Circle(double r);
virtual double getArea();
private:
double _r;
};
Rectangle::Rectangle(double h, double w) {
_h = h;
_w = w;
}
Circle::Circle(double r) {
_r = r;
}
double Rectangle::getArea() {
return _h * _w;
}
double Circle::getArea() {
return _r * _r * 3.142;
}
int main(int argc, char** argv) {
Shape* s1 = new Circle(2.0);
Shape* s2 = new Rectangle(3.0, 4.0);
cout %26lt;%26lt; "s1 area: " %26lt;%26lt; s1-%26gt;getArea() %26lt;%26lt; endl;
cout %26lt;%26lt; "s2 area: " %26lt;%26lt; s2-%26gt;getArea() %26lt;%26lt; endl;
delete s1;
delete s2;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment