Bernal Gonzalez
Bernal Gonzalez

Reputation: 49

C++ Inheritance and Casting

I have these two classes in C++

Problema which is my superclass

class Problema
{
    protected:
        string tipo;
        int N;// GT1 # vertex ; SP5
        int M;// GT1 # edges  ; SP5
        int K;// GT1 covering ; SP5
        Problema *Hijo;

    public:
        //void readProblema(std::ifstream& file); // Lee un problema de un archivo
        void Print();
        Problema(std::string name);
        Problema();
        int geneSize(); // tama˜no del gen
        float fitness(gene x); // c´alculo del fitness
        std::string name; // hilera que indica el nombre del problema
        void readProblema(std::ifstream& file);
        Problema* getHijo(){return Hijo;}
        string getTipo(){return tipo;}
        int getN(){return N;}
        int getM(){return M;}
        int getK(){return K;}
        int toint(std::string s);
};

and GT1 which is a subclass of Problema

class GT1 : public Problema
{
    public:
        void Print();
        GT1(int N,int M, int K,int **arcos);
        int** getArcos(){return arcos;}
    private:
        int **arcos;
};

So what is the proper way of calling the getArcos() method if I want to do this:

Problema *Prob= new Problema();

Prob->Hijo = new GT1(X,Y,Z);

Problema *P = Prob->getHijo();

int **arcos = (GT1)P->getArcos();

Upvotes: 0

Views: 139

Answers (1)

Kamajii
Kamajii

Reputation: 1878

First, you are seemingly assigning to a protected member Hijo from outside the class, which is bad practice and/or does not work. You should use a setter instead, imho.

Second, your core problem is downcasting along the inheritance hierarchy: You have a pointer-to-a-base-class and want to use it like it was a pointer-to-derived-class. This, in principle, is perfectly possible. There are two options:

  • Use static_cast iff you know for sure that the pointer-to-base-class actually points to some object of the derived class.
  • Use dynamic_cast otherwise. This needs RTTI compiled in but is safe and returns a null pointer if the pointer cannot be casted.

As stated in the comments above, you design might look broken. Maybe consider using virtual functions.

Upvotes: 3

Related Questions