samedi 26 août 2023

c++ pattern design inheritance confusion

I want to create a hierarchy of classes that are derived from "genericClass". My problem is that I want to derive classes like "person", "car"... all of the derived classes have specific methods lets suppose:

Person -> getAge(), getSalary()

Car -> getEngine(), getMaxSpeed()

So when I create a "genericClass" pointer I would like to be able to access those functions (remember that they are not defined as virtual in "genericClass").

As far as I know the problem can be solved just by marking them as virtual in the genericClass or casting but I would like to know if a third solution exist.

#pragma once
#include <iostream>
#include <string>
using namespace std;

class genericClass {
 private:
 public:
  genericClass(){};
  ~genericClass(){};
};

class person : public genericClass {
 private:
  int age;
  double salary;

 public:
  person(int a, double b) : genericClass{}, age{a}, salary{b} {}
  ~person() {}

  int getAge() const { return age; }
  double getSalary() const { return salary; }
};

class car : public genericClass {
 private:
  string engine; // string is just a random type for this problem
  double maxspeed;

 public:
  car(string a, double b) : genericClass{}, engine{a}, maxspeed{b} {}
  ~car() {}

  string getEngine() const { return engine; }
  double getMaxSpeed() const { return maxspeed; }
};

int main() {
    genericClass* object = new person{23, 100};
    cout << object->getAge(); 
}

as you can see I cant access the methods because genericClass doesn't know about derived classes methods, happening the same for car

As I previously said I can write them as virtual int getAge() const; in the genericClass. This solution would lead to a massive genericClass with too many virtual methods if I want all of the classes to be derived from genericClass.

Aucun commentaire:

Enregistrer un commentaire