Polymorphism: Difference between revisions

→‎{{header|C++}}: includes added, pointers deleted
m (→‎{{header|Raku}}: .perl not needed)
(→‎{{header|C++}}: includes added, pointers deleted)
Line 604:
 
=={{header|C++}}==
<lang cpp>class#include Point<cstdio>
#include <cstdlib>
{
 
protected:
class Point {
protected:
int x, y;
 
public:
Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
Point(const Point& &p) : x(p.x), y(p.y) {}
virtual ~Point() {}
const Point& operator=(const Point& &p) {
if (this != &p) {
{
if(this ! x = &p).x;
{ y = p.y;
x = p.x;}
yreturn = p.y*this;
}
return *this;
}
int getX() { return x; }
int getY() { return y; }
intvoid setX(int x0) { x = x0; }
intvoid setY(int y0) { y = y0; }
virtual void print() { printf("Point\n"); }
};
 
class Circle : public Point {
private:
{
private:
int r;
 
public:
Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
virtual ~Circle() {}
const Circle& operator=(const Circle& &c) {
if (this != &c) {
{
if(this ! x = &c).x;
{ y = c.y;
x r = c.xr;
y = c.y;}
rreturn = c.r*this;
}
return *this;
}
int getR() { return r; }
intvoid setR(int r0) { r = r0; }
virtual void print() { printf("Circle\n"); }
};
 
int main() {
Point *p = new Point();
{
Point * pc = new PointCircle();
Point* c = new Circlep->print();
p c->print();
delete p;
c->print();
return 0 delete c;
 
return *thisEXIT_SUCCESS;
}</lang>
 
'''Pattern:''' [[CRTP|Curiously Recurring Template Pattern]]
 
<lang cpp>#include <cstdio>
<lang cpp>// CRTP: Curiously Recurring Template Pattern
#include <cstdlib>
 
<lang cpp>// CRTP: Curiously Recurring Template Pattern
template <typename Derived>
class PointShape
Line 677 ⟶ 681:
 
// compile-time virtual function
void print() const { reinterpret_cast<const Derived*>(this)->printType(); }
};
 
Line 695 ⟶ 699:
return *this;
}
void printType() const { printf("Point\n"); }
};
 
Line 704 ⟶ 708:
public:
Circle(int x0 = 0, int y0 = 0, int r0 = 0) : PointShape(x0, y0), r(r0) { }
Circle(Point p, int r0 = 0) : PointShape(p.xgetX(), p.ygetY()), r(r0) { }
~Circle() {}
const Circle& operator=(const Circle& c)
Line 717 ⟶ 721:
}
int getR() { return r; }
intvoid setR(int r0) { r = r0; }
void printType() const { printf("Circle\n"); }
};
 
int main()
{
PointShape<Point>* p = new Point();
PointPointShape<Circle>* c = new Circle();
p->print();
c->print();
delete p;
delete c;
return 0;
}</lang>
Anonymous user