declaring a CLASS embedded in a VOID

Dnsgm

Baseband Member
Messages
61
I have a class in a void, but I'm having trouble declaring it from main().

Code:
#include <iostream>
using namespace std;

void asdf ()
{
     class member
     {
           public:
                  member ()
                  {
                         cout<< "Hello! \n";
                  }
                  
                  ~member ()
                  {
                          cout<< "Goodbye! \n";
                  }
     };
     
}

int main ()
{
    
    // How do I declare the Class? */
 
    return 0;
}
 
What your code shows is a class that you are declaring inside a function that returns void. It can't legally happen and not get instantiated, used and destroyed inside that function. In other words, the specifications say, you've limited the scope of the class to the scope and lifetime of the function you put it in. So, unless you use it after the function call is made and before the function returns, you lose it;)

Try this again without the void blah() function and braces. The class declaration(actually, definition) itself is correct, it just can't stay and play long because the scope is lost before any useful stuff happens. I hope this helps you out.

Code:
#include <iostream>
#include <cstdlib>  // May need this for the pause statement to work.
using namespace std;

//void asdf () This isn't needed here and creates a problem.
// {  Ditto
     class member  // This begins the declaration AND DEFINITION of class           {
           public:
                  member ()
                  {
                         cout<< "Hello! \n";
                  }
                  
                  ~member ()
                  {
                          cout<< "Goodbye! \n";
                  }
     };//End of definition of class member.
     
// }  Mustn't forget this!  It'll mess it up.

int main ()
{
    
    /*How do I declare the Class? Roughly, 
       Like this below.  However, you are actually creating 
       an instance or instantiating the class.  It was declared and 
       defined together above.*/

    member Mine;
    /* Note that the virtual constructor is called here. 
        Next line inserted in case you need to see what is happening
        which usually happens working in Dev-C++ */
    system("pause");
    return 0;
// Destructor is called here as program goes out of scope and makes auto call.
}

I hope I've explained it better and helped you out ;)
 
Back
Top Bottom