Initialize a Variable Again.
Posted
by SoulBeaver
on Stack Overflow
See other posts from Stack Overflow
or by SoulBeaver
Published on 2010-06-01T06:49:13Z
Indexed on
2010/06/01
6:53 UTC
Read the original article
Hit count: 249
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?
© Stack Overflow or respective owner