1 2 3 4 5 6 7
|
class Class2{
public:
int change(){
object1.integer1 = 10;
return 0;
}
};
|
This is a class definition. You are explaining to the compiler what this new kind of object looks like. You're saying this new kind of object is called an object of type Class2, and it contains the following things:
a function, that accepts no input and returns an int.
So then the compiler gets to that function, and inside this function you try to use the object named
object1. Inside any function, the following things exist:
1) Global variables
2) Variables passed into that function
3) Variables created in that function.
object1 is NONE of these things. It does not exist within that function.
shouldn't Class2 (or any of it's instances) be able to access integer1? as both object2 and integer1 are members of Class1? |
That's insane. You're suggesting that any class should be able to access data in any other class. Like it's some kind of giant global-variable soup in which all contents of all classes are available everywhere. What is Class2's relationship to class1? Nothing. There is no relationship. Just because Class1 contains an object of type Class2 does not mean suddenly that all instances of Class2 can somehow see into that Class1 object.
What if i had this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
class Class2{
public:
int change(){
object1.integer1 = 10;
return 0;
}
};
class Class1{
public:
int integer1;
Class2 object2;
};
int main(){
Class2 object2;
return 0;
}
|
In this code, I never even made an object of type Class1. How could object2 possibly access object1 given that object1 doesn't even exist?