c++ pattern design inheritance confusion [closed]

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.

  • I can’t see, what the purpose of genericClass actually should be? Are you asking about kinda TObject as provided in c++ builder or Delphi??

    – 

  • It does seem like some quality, focused time with a study of general C++ principles and programming practices will be of great benefit here. Putting using namespace std; in a header file will always end in tears, at some point. Don’t do that.

    – 

  • @EV2 Focus on interfaces (pure virtual class in c++), and eventually multiple implementations, if there’s actually need to support more than one with a specific class.

    – 




  • OOP as implemented by C++ doesn’t support the notion of “generic class” (superclass of all other classes). Simply don’t have any such thing defined and you will be all set. Any attempt to introduce one will lead to a broken design.

    – 




Leave a Comment