Click to See Complete Forum and Search --> : Inner class issues


DishumTheGreat
April 2nd, 2002, 05:25 AM
Can any one help me!!!
I have an inner class in the main class. There is some variable declared in main class some thing like this

class MainClass
{
class Inner
{
public :
Display();
};

public:
int x;
Inner inObj;
};



I need to know that is there any way to access x from function display.

Alexis Moshinsky
April 2nd, 2002, 05:46 AM
Hi,

this will work.

int* ptrToX = ((int*)this) - 1;

But be careful, however it seems to be only way,
it's not a legal way to access data-member, and generally speaking against OO.

NMTop40
April 2nd, 2002, 10:44 AM
you can access x from Display because it is public in MainClass, but you will also need an instance of MainClass through which to access it, as x is a member of MainClass and not of Inner.

There is not necessarily a one-to-one relationship between MainClass and Inner. While every MainClass has an Inner, the converse is not true - although the class is private, there is nothing to stop any member functions of MainClass creating new ones.

You could, of course, pass in a pointer to the constructor of Inner. You will get a warning, but you can ignore it. Thus:


class MainClass
{
class Inner
{
public :
Inner( MainClass * outer=0) : m_outer(outer) {}
Display();
MainClass * m_outer; // or make it private
};
//
public:
int x;
Inner inObj;
MainClass();
};
//
// MainClass constructor (in MainClass.cxx)
//
MainClass::MainClass()
: inObj( this ) // will raise a warning but ignore it or pragma it out
{
}





The best things come to those who rate

jwbarton
April 2nd, 2002, 10:50 AM
You could try something like:


#include <iostream>

using namespace std;

class MainClass
{
class Inner
{
int& m_x;

public:
Inner( int& x ) : m_x(x)
{
}

void Display()
{
cout << "x = " << m_x << endl;
}
};

public:
MainClass() : inObj(x), x(5)
{
}

int x;
Inner inObj;
};


int main(int argc, char* argv[])
{
MainClass object;

object.inObj.Display();

return 0;
}




This example puts a reference to the x variable into the inner class (which is initialized by the MainClass constructor).

The Display routine then accesses the MainClass::x member by using a reference.

Best regards,
John