Skip to main content
gamedev.net
🔒 Locked

Class within a Class

Started by mk83 4 replies 500+ views
Original Post
mk83
mk83
Hi guys, I have the following problem, lets say you have the following code. class test { int testvar; class test2 { int testfunc(); } } test::test2::testfunc() { testvar = 3; return; } when you try to compile, it will not let you change testvar, as it says that it is not yet declared! Is there a way to access the variable, without handing it to the function as a parameter? Thanks, MK83
Palidine
Palidine
nope, not easily. it''s a scope issue. testvar is outside the scope of class test2. what exactly are you trying to do? there is undoubtably a better method than having an internal class.

-me
SiCrane
SiCrane
No, not really. An instance of an inner class does not necessarily have any ties to the outer class. If you want to connect a specific instance of an inner class to a specific instance of an outer class you need to do so explicitly. Either pass a pointer or reference to the function or store a pointer or reference inside the inner class''s constructor.
mk83
mk83
Thanks guys,

I used your idea and created a ref to the calling class, in my second class,

Looks like it''s gonna work,

Thanks for the quick replies,

MK
Evil Steve
Evil Steve
Just to re-iterate whats been said: Declarign a class inside another class doesn''t mean anything - you''re more or less just as well declaring 2 seperate classes (Although it will obviously look better for some situations)
outRider
outRider
Perhaps you''ve seen Java code that does something like that. In Java inner classes can access their outer class because a reference to an outer object is passed to the inner object, it''s not just a scope issue but the inner and outer classes are coupled. In C++ you need to do it explicitly, and you might also have to declare the inner class a friend of the outer class.

------------
- outRider -

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.