I am attempting to access members of an object that I have created within another object but the proper syntax is eluding me. Or, perhaps the problem is how I am creating the inner class?
This should be all the relevant bits. I have tried many formats for my call to the inner class and keep getting variations on the error following the code. Any help would be appreciated.
#include <iostream>
#include <memory>
usingnamespace std;
class InnerClass {
public:
InnerClass() { val = 10; }
int getval() { return val; }
protected:
int val;
};
class OuterClass {
public:
OuterClass() {this-> Inner = 0;}
InnerClass * Inner;
};
int main() {
OuterClass * Outer;
std::cout << Outer.Inner.getval() << std::endl;
return 0;
}
request for member ‘Inner’ in ‘Outer’, which is of non-class type ‘OuterClass*’
I should probably add, that the reason I am creating the classes as empty pointers is that I actually have child classes I am filling them with, however I am fairly certain that part is functioning correctly and my problem is the actual syntax of accessing the nested object members.
#include <iostream>
#include <memory>
usingnamespace std;
class InnerClass
{
public:
InnerClass()
{
val = 10;
}
int getval()
{
return val;
}
protected:
int val;
};
class OuterClass: public InnerClass
{
};
int main()
{
OuterClass * Outer;
std::cout << Outer->getval() << std::endl;
return 0;
}
Assigning the outerclass as a child like this is probably better than making the internal pointer to it although it does this behind the scenes anyway.
By the way your protected val is accessible to the derived class in a protected: mode.
make it private: to prevent this.
Edit: there is no information about the kind of relationship, ¿why did you suggest inheritance?
You are right, there was no information that it should be inherited. I sort of got in my head that it was what he was after because of the inner and outer variable names implied to me that he did indeed want to build classes from a base class.
But yes as ne555 stated you will not want this if you are pointing to a single object from many objects.