|
-
Nov 20th, 2003, 03:45 PM
#1
Thread Starter
Stuck in the 80s
[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.
-
Nov 20th, 2003, 03:52 PM
#2
Thread Starter
Stuck in the 80s
I just realized my original switch code doesn't even compile.
-
Nov 20th, 2003, 05:33 PM
#3
something like this:
Code:
public class cStudent
{
public:
virutal void getSpecialInfo() {};
virtual /* other functions shared amongst students */
};
public class cSophmore : public cStudent
{
public:
void getSpecialInfo() { /* .... */ };
/* .... */
}
///////////////////////////////////////
cStudent 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;
}
cNewStudent.getSpecialInfo();
Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.
-
Nov 20th, 2003, 08:28 PM
#4
Thread Starter
Stuck in the 80s
Thanks, I think I got it working using that idea.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|