0

(C++) what is the best way of getting a child class from parent class for example: im making a game engine so i have classes called mesh, light, and camera and they are all different but they have 1 thing in common, thay all have transformations, so i made a class called node and mesh, light and camera all extend node. (node holds common data like transformations and can only hold ONE of these 3 types). so i will have a heirarchy of these nodes(transforms). so later after i iterate through this heirarchy, at a certain node how can i get my mesh or light, because how do i know if a particular node is holding a mesh or light or camera because node is a generic class and can hold all 3 of these. long story short is there a way to know what type of object node is holding, and if I find that out how can i get the mesh object or light object from node??? thanks in advance!

Example Code:

class Node // generic class
{
    private:
       //hold transformation data
};

class Mesh : public Node
{
    //mesh information
};

class Light : public Node
{
//mesh information
};

...

int Main()
{
    Node node;
    //node will be initialized with a mesh, light or camera


   //so how do i know if this node is a mesh, light, or etc...
   //and how to get the mesh/light/camera data

}

zmac
  • 19
  • 4
  • The point of defining an interface like `Node` is that you don't _need_ to know exactly which derived class you're pointing to, you can call the methods that belong to the interface and they will be dispatched to the appropriate concrete object. However what few snippets of your code have posted indicate that you'll be suffering from [object slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing). Unfortunately the subject of polymorphism in C++ is a bit too broad to be answered in a single SO question. – Nathan Pierson Nov 15 '21 at 06:34
  • 1
    If `Mesh` and `Light` can't be described by the same interface, you've run afoul of the [Liskov Substitution Principle](https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle) – user4581301 Nov 15 '21 at 06:47

1 Answers1

0

The best way is then parent don't know anything about interface extensions in children. Are you sure Node should be parent? One option is make Node container (hand made or standard like variant) for predefined set of transformations. E.g.:

class Mesh
{
    //mesh information
};

class Light
{
//mesh information
};

using Node = std::variant<Mesh, Light>;

int Main()
{
    Node node{Mesh{}};
    // ....
    if(const Mesh* m = std::get_if<Mesh>(&node)) {
      // do mesh related things
      m->transform();
    } else if (const Light* l = std::get_if<Light>(&node)) {
      // do light related things with l
    }
    return 0;
}

Another option is left class hierarchy and use dynamic_cast for cast base class to one of child. But usage dynamic_cast is always indicate broken design

slonma
  • 115
  • 1
  • 5