lundi 12 août 2019

Is it possible to type cast from parent class this pointer to child class

I have an requirement to access child class variables from parent class member function.

I tried doing dynamic cast on parent class "this" pointer to dynamic cast but I get following compilation error: main.cpp: In member function ‘void Parent::do_something()’: main.cpp:24:45: error: cannot dynamic_cast ‘(Parent*)this’ (of type ‘class Parent*’) to type ‘class Child*’ (target is not pointer or reference to complete type) Child *child = dynamic_cast(this); Is there any possible way to achieve my requirement.

#include <iostream>

using namespace std;

class Child;

class Parent {
    public:
    Parent() {};
    virtual ~Parent() {};
    void do_something();
};

void Parent::do_something()
{
    Child *child = dynamic_cast<Child*>(this);
    child->i = 10;
}

class Child : public Parent {
    public:
    int i = 0;
    void do_something() {}
    void do_something1() 
    {
        Parent *parent = static_cast<Child*>(this);
        parent->do_something();
    }
};

int main()
{
    Child child;
    child.do_something1();
    printf ("Value of i: %d", child.i);

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire