One of the cool things about object oriented programming is that you can derive a class from an existing class. this allows you to have most of the class built from an existing class, and not need to rewrite the whole class, only the new parts.
Additionally, if the original class, called the base class is updated, all of the derived classes are updated as well. This is how using inheritance, the concept of deriving a class from a base class, is far superior than lets say, copy and pasting.
We can think of this as a parent-child relationship. Where the base class is the parent, and the derived class is the child. The child inherits the properties and methods of the parent. In fact this is called inheritance.
Let’s consider our Circle class from before. If we were to build a rectangle class, they would share a lot of the same properties. For example the x,y position for the center, a color perhaps. They would need some of the same functions, like getArea(). Of course, how they calculate those functions are may be different, and inheritance allows for us to handle those situations as well.
In fact, property wise, a circle and a square have more in common if you thing about it.
So you could have a GenericGeometric class, which Circle and Square extend, and then Rectangle extends Square.
Let’s look at what the GenericGeometric header would look like:
#pragma once
#include <iostream>
using namespace std;
class GenericGeometric
{
public:
GenericGeometric();
GenericGeometric(double size);
GenericGeometric(double size, string color);
GenericGeometric(double size, string color, double x, double y);
string getColor() const;
double getX() const;
double getY() const;
double getSize() const;
void setSize();
void setXY(double x, double y);
void setX(double value);
void setY(double value);
void setColor(string value);
double getDistance(GenericGeometric g);
double getArea();
private:
string color;
double size;
double x, y;
};
And a section of the associated .cpp file would look like:
#include "GenericGeometric.h"
GenericGeometric::GenericGeometric()
{
this->color = "white";
this->size = 1;
this->x = 0;
this->y = 0;
}
GenericGeometric::GenericGeometric(double size)
{
this->color = "white";
this->size = size;
this->x = 0;
this->y = 0;
}
GenericGeometric::GenericGeometric(double size, string color)
{
this->color = color;
this->size = size;
this->x = 0;
this->y = 0;
}
GenericGeometric::GenericGeometric(double size, string color, double x, double y)
{
this->color = color;
this->size = size;
this->x = x;
this->y = y;
}
Base vs Derived Classes was originally found on Access 2 Learn
One Comment
Comments are closed.