I was wondering if someone could give an example of how to use something like:
or something like that.Code:class TestClass
{
public:
TestClass();
~TestClass();
class Test
{
int x;
Test();
~Test();
void Test2(int x);
};
void Test3(int x);
};
Printable View
I was wondering if someone could give an example of how to use something like:
or something like that.Code:class TestClass
{
public:
TestClass();
~TestClass();
class Test
{
int x;
Test();
~Test();
void Test2(int x);
};
void Test3(int x);
};
Code:class Test
{
int x;
Test();
~Test();
void Test2(int x);
};
class TestClass
{
public:
TestClass();
~TestClass();
Test test;
void Test3(int x);
};
that only works for public functions then right? if it was somehow declared inside the other class couldn't it use the private declerations too? (assuming there were private declerations) or would the need inheritance?
There's nothing wrong with inner classes...used in the right circumstances, they can be quite usefull.Quote:
Originally posted by bennyandthejetsCode:class Test
{
int x;
Test();
~Test();
void Test2(int x);
};
class TestClass
{
public:
TestClass();
~TestClass();
Test test;
void Test3(int x);
};
To use the OPs original code (with a few practical changes)
Code:#include <iostream>
class TestClass
{
public:
TestClass(){}
~TestClass(){}
class Test
{
public:
int x;
Test(){}
~Test(){}
void Test2(int x_){x = x_;}
};
int x;
void Test3(int x_){x = x_;}
};
int main(int argc, char *argv[])
{
TestClass::Test foo;
foo.Test2(10);
std::cout << foo.x << std::endl;
TestClass bar;
bar.Test3(20);
std::cout << bar.x << std::endl;
}
So it's like a namespace is it? You can group together a bunch of things?
BTW, you forgot to return from main() :p.
The inner class can be addressed like a namespace, but it can be handy when you want a private inner class that's more or less invisible to the user of the outer class.....have a peek at this thread I did a while ago on proxy classes - http://cboard.cprogramming.com/showt...ighlight=proxyQuote:
Originally posted by bennyandthejets
So it's like a namespace is it? You can group together a bunch of things?
You dont need to if your compiler is fairly C++ complient. Only old non complient compilers like VC++6 force the explicit return from main.Quote:
Originally posted by bennyandthejets
BTW, you forgot to return from main() :p.
The most common usage I've seen for nested classes is to hide the implementation of the class completely. For example:
Now, the 'data' struct is implemented in the source file. 'data_ptr' is the only (except in exceptional circumstances) private data member of A. In a large project, this means that if you change the internal data of the class, you only need to recompile the class and relink the program, not relink everything that depends on A.hCode:// In the header file.
class A
{
public:
// ... Stuff ...
private:
struct data;
data* data_ptr;
};
I've seen classes declared within classes to set up classes for exceptions to throw like OutOfRange and such.