external member function implementation in local class

arkangel's Avatar, Join Date: Aug 2008
Light Poster
I was reading the std and i can't figure out if this is possible at all . I want to have a local class in a function , one of the member functions is rather long so I want to implement it outside of the function.


Code:
#include <iostream>

using namespace std;

int foo(){

       class intClass{
                  int a, b;
            public:
                  intClass() {a=1; b=1;}
                  int doSome_over_a_b(){/* doSome_over_a_b */}
             
     };
   intClass  X;
   int y=X.doSome_over_a_b();
   /*some other  foo stuff*/
}

/*
   I want to put intClass::doSome_over_a_b
   here or in a *.C  file
*/
int main (void)
{
   foo();

}

How can I implement doSome_over_a_b outside of foo keeping the declaration in intClass as if it were a normal class ?
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
If the issue is just that you don't want to clutter foo(), why not write the code in a separate file and #include it? So:
Code:
int foo(){

       class intClass{
                  int a, b;
            public:
                  intClass() {a=1; b=1;}
                  int doSome_over_a_b()
                  {
#include "intClass_doSome_over_a_b_code.cpp"
                  }
       }
}
arkangel's Avatar, Join Date: Aug 2008
Light Poster
Thanks I was thinking the same

but the question remains : if that possible at all ?

the std draf in sec 9
"A class can be declared within a function definition; such a class is called a local class" , see declared ,
anyway I try your approach
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Yep, the following compiles and runs perfectly in VS2005:
Code:
void LocalClass()
{
	class wibble{
		char str[32];
	public:
		wibble(char *t){strcpy_s(str,30,t);}
		void prt(){printf("%s\n",str);}
		};
	wibble a("Hello LocalClass");
	a.prt();
}
and if I place void prt(){printf("%s\n",str);} into a separate file foo.txt, the following also compiles and runs without error;
Code:
void LocalClass()
{
	class wibble{
		char str[32];
	public:
		wibble(char *t){strcpy_s(str,30,t);}
#include "foo.txt"
		};
	wibble a("Hello LocalClass");
	a.prt();
}
You can place #includes anywhere; it's just a lexical thing done by the preprocessor so it's not limited to header files only; you can #include whatever you want wherever you want. Probably worth commenting the code though if you're going to do something non-headery with it such as this.