Sie sind auf Seite 1von 8

SES-1

Inheritances and
Polymorphism
Marco A. León Badillo

1/8
Different kinds
of inheritance

• Public
• Private
• Protected

• Common functionalitiy
• Avoid Code duplication

2/8
Example inheritance

class Circle : public Shape


{
public:
Circle(const double ax, const double ay, const double r)
:Shape(ax, ay), radius(r) {}
double get_area(void) const
{
return radius * radius * PI;
}
void print(void) const
{
Shape::print(); cout << " radius: " << radius << endl;
}
private:
double radius;
};

3/8
Constructors and Destructor
Rectangle role in inheritance
Constructor is called when new object is
Shape
created
• Order of constructors:
• First execution in Base class then
Subclass

Destructor is called when created object is


deleted
• Destructor (~) reverse:
• First execution in Subclass then Base
class 4/8
Polymorphism

• Many shapes

5/8
Example polymorphism

class Shape class Circle : public Shape


{ {
public: public:
Shape(const double ax, const double ay) Circle(const double ax, const double ay, const
:anchor_x(ax), anchor_y(ay) {} double r) :Shape(ax, ay), radius(r) {}
virtual double get_area(void) const
virtual void print(void) const {
{ return radius * radius * PI;
cout << “Anchor point is (" << anchor_x << "," << }
anchor_y << ")"; virtual void print(void) const
} {
virtual double get_area(void) = 0; //pure virtual Shape::print(); cout << " Radius: ";
private: }
double anchor_x, anchor_y; private:
}; double radius;
};

6/8
Main Code
int main(void) • Console with virtual function
{
Rectangle r(1, 2, 3.4, 4.5);
Square s(6, 7, 3); Anchor point is: (1,2) length: 3.4 width: 4.5 Area: 15.3
Circle c(4, 2, 4.5); Anchor point is: (6,7) Side: 3 Area: 9
Anchor point is: (4,2) Radius: 4.5 Area: 63.6172
Shape *shape_ptrs[3] = { &r, &s, &c };
unsigned int i;
for (i = 0; i < 3; i++) • Console without virtual function
{
shape_ptrs[i]->print();
at print()
cout << " Area: " << shape_ptrs[i]->
get_area() << endl; Anchor point is: (1,2) Area: 15.3
} Anchor point is: (6,7) Area: 9
} Anchor point is: (4,2) Area: 63.6172

7/8
Pure virtual • Abstract base classes: • Interface classes:
- created by declaring - no object members
functions one or more pure  template
(abstract, virtual functions - just pure virtual
interface) - have object members functions
- only
- Pure virtual functions unimplemented
have no real syntax (as methods
it is =0; incomplete). - not possible to
- can't be used to instantiate that
instantiate objects. class

8/8

Das könnte Ihnen auch gefallen