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!