Results 1 to 4 of 4

Thread: [Resolved] Class Instantiation

Threaded View

  1. #1

    Thread Starter
    Stuck in the 80s The Hobo's Avatar
    Join Date
    Jul 2001
    Location
    Michigan
    Posts
    7,256

    [Resolved] Class Instantiation

    I have a switch statement like this:

    Code:
    switch (iOption) {
        case 1:
            cFreshman cNewStudent = new cFreshman();
            cNewStudent.getSpecialInfo();
            break;
          
        case 2:
            cSophomore cNewStudent = new cSophomore();
            cNewStudent.getSpecialInfo();
            break;
    
         case 3:
            cJunior cNewStudent = new cJunior();
            cNewStudent.getSpecialInfo();
            break;
            
        case 4:
            cSenior cNewStudent = new cSenior();
            cNewStudent.getSpecialInfo();
            break;
    
        default:
            break;
    }
    There's other code involived in the cases, but I just trimmed it to this as an example. Now, to shorten up the code, I wanted to do something like this:

    Code:
    switch (iOption) {
        case 1:
            cFreshman cNewStudent = new cFreshman(); break;
          
        case 2:
            cSophomore cNewStudent = new cSophomore(); break;
    
         case 3:
            cJunior cNewStudent = new cJunior(); break;
            
        case 4:
            cSenior cNewStudent = new cSenior(); break;
    
        default:
            break;
    }
    
    cNewStudent.getSpecialInfo();
    // do other stuff with cNewStudent
    But that obviously wont work, since cNewStudent is only defined within the scope of the case statement.

    So I'm wondering if there's any other way to do it? Like:

    Code:
    cClassName cNewStudent;
    switch (iOption) {
        case 1:
            cNewStudent = new cFreshman(); break;
          
        case 2:
            cNewStudent = new cSophomore(); break;
    
         case 3:
            cNewStudent = new cJunior(); break;
            
        case 4:
            cNewStudent = new cSenior(); break;
    
        default:
            break;
    }
    
    cNewStudent.getSpecialInfo();
    // do other stuff with cNewStudent
    I know that doesn't make much sense, but can I setup the class without defining what type it is, and then define it's type in the case statement? Or anything else like this?

    I know it's a longshot, but I figured I'd ask anyways.
    Last edited by The Hobo; Nov 20th, 2003 at 08:29 PM.
    My evil laugh has a squeak in it.

    kristopherwilson.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width