That may sound a little confusing. Basically, I have a function
CCard newCard()
{
/* Used to store the string variables intermittantly */
std::stringstream ssPIN, ssBN;
int picker1, picker2;
int pin, bankNum;
/* Choose 5 random variables, store them in stream */
for( int loop = 0; loop < 5; ++loop )
{
picker1 = rand() % 8 + 1;
picker2 = rand() % 8 + 1;
ssPIN << picker1;
ssBN << picker2;
}
/* Convert them */
ssPIN >> pin;
ssBN >> bankNum;
CCard card( pin, bankNum );
return card;
}
that creates a new CCard variable and returns it to the caller
CCard card = newCard();
My teacher advised me that doing this is a violation of OOP principles and has to be put in the class. He told me to use this method as a constructor. Which I did:
CCard::CCard()
{
m_Sperre = false;
m_Guthaben = rand() % 1000;
/* Work */
/* Convert them */
ssPIN >> m_Geheimzahl;
ssBN >> m_Nummer;
}
All variables with m_
are member variables. However, the constructor works when I initialize the card normally
CCard card();
at the start of the program. However, I also have a function, that is supposed to create a new card and return it to the user, this function is now broken.
The original command: card = newCard();
isn't available anymore, and card = new CCard();
doesn't work. What other options do I have? I have a feeling using the constructor won't work, and that I probably should just create a class method newCard, but I want to see if it is somehow at all possible to do it the way the teacher wanted.
This is creating a lot of headaches for me. I told the teacher that this is a stupid idea and not everything has to be classed in OOP. He has since told me that Java or C# don't allow code outside of classes, which sounds a little incredible. Not sure that you can do this in C++, especially when templated functions exist, or generic algorithms. Is it true that this would be bad code for OOP in C++ if I didn't force it into a class?
EDIT:
I would like to thank everyone for their helpful answers! However, I believe that my phrasing of the question is a little screwed up, and I think people don't understand what I am looking for.
I do not want to initialize another member of type CCard. I want to intitialize
CCard card
once and then give card
new values through the constructor, because this is what the teacher told me to do. I do not want to create a new CCard object, just use the same variable with new values over again.
This is why I said it probably won't work with the constructor. So I have a function that is supposed to take the initialized variable card
and then call the constructor again( "What?" is what I told the teacher ) and then give it new values.
Example code:
void foo()
{
/* Initialize card with constructor */
CCard card;
/* Give it new values through the constructor AGAIN... */
card;
}
This is the actual question. I'm sorry if I confused everybody xD