what I am trying to do is:
Sub
class object in Base
class.Sub
class access Base
class'es variablesBase.h
#include "Sub.h"
class Base
{
Sub subobject
int x;
}
Sub.h
#include Base // to acces x from .cpp file
class Sub: public Base
{
void changevar();
}
Sub.cpp
#include "Sub.h"
// I tried to include base in here but that did not work either
void Sub::changevar()
{
x++;
}
But I keep getting undefines base class and undefined undeclared x error. How can I solve this?
What if you store the suboject as a pointer instead?
You will need to also
However it seems a bit odd a base have a reference to a subclass, it breaks the whole point of inheritance and if you are needing to do this, then you should reconsider if what you are doing is correct.
Also note, the Sub will have its own Base as part of it so the Base part of the subobject will not be the same as the outer Base.
e.g. if Base itself had an integer called Y, then we would have the Y of Base, but a separate Y for subobject also.
Maybe explain a bit better why the base class needs a copy of a subclass?
Rough code sketch:
Base.h
#include "Base.h"
class Sub;
class Base
{
public:
Sub* subobject;
Base();
~Base();
void createSub();
};
Base.cpp
#include "Base.h"
#include "Sub.h"
Base::Base()
{
subobject = new Sub();
}
Base::~Base()
{
delete subobject;
}
void Base::createSub()
{
if (subobject)
return;
subobject = new Sub();
}
Sub.h
#include "Base.h"
class Sub : public Base
{
void changevar();
int x = 0;
};
Sub.cpp
void Sub::changevar()
{
x++;
}