Bakya
Bakya

Reputation: 11

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 child class 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<Child*>(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;
}

Upvotes: 1

Views: 137

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

The important part of the error message is this:

target is not pointer or reference to complete type

[Emphasis mine]

You need the full definition of the Child class for it to work.

The solution is to rearrange your code so that the do_something function is defined (implemented) after the Child class definition:

class Child : public Parent { ... };

void Parent::do_something() { ... }

Upvotes: 4

Related Questions