Search code examples
c++inheritancepointersparent

C++ Changing the parent class within the child class


My very first post here! I have been using this site for many years as a reference and to find solutions to common problems. Unfortunately this problem I am facing is one that have not been found here yet! So here it is. I have been working on a project for some time now. My program has several thousand lines of code so I will not post it all here. Basically, I have a subclass in which I wish to change the parent class to one that has been already initialized in my code some place. I am not sure if this is possible or if it is good code practice. But I will let you guys be the judge of that! Here is the problem I am facing:

#include <stdio.h>

class Base

    public:
        int data;
        Base(int);
};

class Child : public Base
{
    public:
    Child(void);
        void run(Base*);
};

Base::Base(int var)
{
    data=var;
}


void Child::run(Base* base)
{
      this = base //I know that you can create a reference to the parent class
                    //by casting this pointer to a Base pointer, but was wondering
                   //if you can do this the other way around. 
    printf("%d\n",Base::data);
}

int main()
{
Base* base1 = new Base(5);
Base* base2 = new Base(3);
    Child one();

one.run(base1);

    delete base1;
    delete base2;
    base1=0;
    base2=0;
    return 0;
}

So if this compiles(which it does not) it would outputt something like 5 and if I change the run method parameter to base2 it should print something like 3. Is this possible? Thank you!


Solution

  • No, you cannot do things like that. This is a READ-ONLY pointer. The line

     this = base;
    

    WILL generate a syntax error.

    Base classes in C++ are static. They cannot be changed at run time.

    Although, if your classes (both the base and the child) do not have virtual functions, the follwoing WILL work:

    (Base&)*this = *base;
    

    At the same time I would discourage you to do this. The reason of discouraging is because such code would be highly vulnerable for changes. For example, if virtual method will be added to either of the classes, then the VMT will be overwritten. This may not work with multiple inheritance. In my experiments with MSVC I noticed that sometimes it changes the order of base classes in the binary layout of the class.

    In other words, this can be used if you are absolutely sure of the layout that is used by compiler. If you are sure that compiler will not change this layout in the future. If not, better avoid this.

    The right approach is to create a special method and copy in the data field by field.