Search code examples
javac++oopcode-reuse

why is it a bad practice to inherit every class, and then simply make a single object of derived class to do all operations in oop?


I'm new to c++, i got a simple question to implement a bakery, having products(ex. pastry,donuts) and baking machine to work on those products(calculate calories, baking temperature etc). I just made two classes, wrote all the functions, and then inherited them to make a single class, and did my work but my mentor is not happy with that way. i want to ask what's wrong there? How does it affect code re-usability?? Here are the function prototypes which I made. P.s. I'm new to OOP

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
#include <map>
#include <time.h>
using namespace std;
int minimum(vector<int>);
struct Inventory
{
    string Name;
    map<string,float> inputfromfile;
};
class BakedItem
{
public:
    BakedItem(){}
    ~BakedItem() {}

protected:
    string Item;
    float TemperatureForBakingItem;
    vector <string> ShapesPossible;
    vector <string> Ingredients;
    void GetIngredients(string);
    void ShapesPossibility(void);
    void GetTemperature(string);
};
class Bakery:BakedItem
{
public:
    Bakery(){}
    ~Bakery(){}
    time_t * ViewManufactureDate(void);
    float ViewPrice(void);
    void GetInput(string);
    void ViewShapesPossible(void);
protected:
    time_t DateManufacture;
    float PriceOfItem;
    float Calories;
    void GetManufactureDate(void);
    void CalculateCalories(void);
    void CalculatePrice(void);
    void GetInventory(void);
};

Solution

  • Because it not only ignores the relationship between different classes, but creates incorrect relationships. Inheritance is an "is-a" relationship. When Cat implements Animal, the relationship is "Cat is-an Animal".

    This is not true for your OOP. Bakery should not be a BakedItem. Rather, a Bakery has zero or more baked items. Otherwise, what does it mean for Bakery to have a list of possible shapes? Are we talking floor plans? When you extend a class, the subclass has to abide by the superclasses' contract.

    For example, the BakedItem class might have a description of:

    This class represents a food item which has been heated in an oven at a specific temperature for a specific amount of time.

    If Bakery extends BakedItem, does that mean that the bakery itself has been put into some giant building-sized oven?

    ... You can see how following the logical relationships as currently described by your code quickly becomes nonsensical.


    Remember, fields are a "has-a" relationship, and inheritance represents an "is-a" relationship; Use these to model your objects accurately, because it will make more sense as to what the purpose of each class does and how each method works and interacts with the objects.