2. Inheritance:
Base and Derived Classes
Inheritance is the
process of creating a
new classes (derived
classes) from existing
classes (based classes).
6. No-Inheritance: Shapes
class Rectangle{
Polygon private:
int numVertices;
int xCoord, yCoord;
public:
Rectangle void set(int x, int y, int nV);
Triangle
int area();
};
class Polygon{
private: class Triangle{
int numVertices; private:
int xCoord, yCoord; int numVertices;
int xCoord, yCoord;
public:
public:
void set(int x, int y, int nV);
void set(int x, int y, int nV);
int area();
int area();
}; };
7. Inheritance: Shapes
class Polygon{
Polygon protected:
int numVertices;
float xCoord, yCoord;
public:
void set(int x, int y, int nV);
};
Rectangle
Triangle
class Rectangle : public Polygon{
public:
int area();
};
8. Inheritance: Shapes
class Polygon{
Polygon protected:
int numVertices;
float xCoord, yCoord;
public:
void set(float x, float y, int nV);
};
Rectangle
Triangle
class Triangle : public Polygon{ class Rectangle : public Polygon{
public: public:
int area(); float area();
}; };
9. Inheritance: Syntax
Syntax:
class DerivedClassName : access-level BaseClassName
where
access-level specifies the type of derivation
private by default, or
Public
Any class can serve as a base class
Thus a derived class can also be a base class
10. Inheritance: Syntax
Syntax:
class DerivedClassName : access-level BaseClassName
Example:
class BaseClass
{
}
class DerivedClass: public BaseClass
{
}
14. Overriding member functions
Member functions in a derived class can have the same
names as in the base class
When the same function exists in both the base and
derived classes, the function in the derived class will be
executed.
In order to call a function in the base class use the use the scope resolution
operator, e.g.,
Stack :: push()
Name Scope
Call to a member function
(base class) resolution
in base class
17. Inheritance: Shapes
x
class Point{
Point
y protected:
int x, y;
public:
Circle 3D-Point void set (int a, int b);
x x
};
y y
r z
class Circle : public Point{ class 3D-Point: public Point{
private: private:
double r; int z;
}; };