[Solved] Confused on code

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

[Solved] Confused on code

Post by zodiac976 »

I was sitting around messing with class variables making
up a "level up" piece of code.

Code: Select all

#include <iostream>
using namespace std;

class Character
{
	public:
		Character() {};
		Character(int, int, int, int, int);
		void dispStats();
		void updateLevel();
		void loc();
//Accessors
		inline void setLevel(int temp) {level = temp;}
		inline void setHealth(int temp) {health = temp;}
		inline void setMana(int temp) {mana = temp;}
		inline void setExp(int temp) {exp = temp;}
		inline int getLevel() const {return level;}
		inline int getHealth() const {return health;}
		inline int getMana() const {return mana;}
		inline int getExp() const {return exp;}
	private:
		int level;
		int health;
		int mana;
		int exp;
		int maxExp;   //not worried about max health and mana for now.
	protected:
};

Character::Character(int defLevel, int defHealth, int defMana, int defExp, int defMaxExp):
	level(defLevel),
	health(defHealth),
	mana(defMana),
	exp(defExp),
	maxExp(defMaxExp)
{}

void Character::updateLevel()
{
	Character character;

	if(exp > maxExp)
		character.setLevel(level++);

	return;
}

void Character::dispStats()
{
	Character character;

	cout << level << endl;
	cout << health << "/" << health << endl;
	cout << mana << "/" << mana << endl;
	cout << exp << "/" << maxExp << endl;

	return;
}

void Character::loc()
{
	cout << "\nInside loc function\n\n";
	//If I use dispStats() inside here the data gets erased.

	return;
}

int main()
{
	Character character(1, 50, 20, 0, 5);

	character.updateLevel();
	character.dispStats();

	cout << "\nTesting Level Up..press any key to gain 10 exp";
	cin.get();

	character.setExp(10);
	character.updateLevel();
	character.setExp(0);
	character.loc();
	character.dispStats();

	return 0;
}
I am confused about one thing why is this line character.dispStats()
before return 0; keeping its data after I return from a function?

As far as I remember after returning a variable loses its data....
probably a stupid question...
Last edited by zodiac976 on Mon Jun 29, 2009 5:31 pm, edited 1 time in total.
User avatar
ultimatedragoon69
Chaos Rift Regular
Chaos Rift Regular
Posts: 122
Joined: Tue Oct 28, 2008 1:57 pm
Current Project: Pangea's quest (text ~tile~ based rpg)
Favorite Gaming Platforms: Dreamcast, PC, playstation 1, Virtual Boy, Snes
Programming Language of Choice: c++
Contact:

Re: Confused on code

Post by ultimatedragoon69 »

Your variables are global. Only variables within the function that was first initiated are erased. (its like 3 am so please don't take my word for it) anyway good night.
User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

Re: Confused on code

Post by zodiac976 »

I don't know about that, my variables are private so they
can't be global unless I make them public or move them
outside the class. If I call dispStats() inside loc() the
variables lose their data but when it returns the data
is still there..that is what's confusing me. Maybe it's
the constructor.
User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

Re: Confused on code

Post by zodiac976 »

I was messing around with that code again and I actually
got a pointer to work with it although I think a reference
would be better.

Code: Select all

#include <iostream>
using namespace std;

class Character
{
	public:
		Character() {};
		Character(int, int, int, int, int);
		void dispStats();
		void updateLevel();
		void loc(Character *);
//Accessors
		inline void setLevel(int temp) {level = temp;}
		inline void setHealth(int temp) {health = temp;}
		inline void setMana(int temp) {mana = temp;}
		inline void setExp(int temp) {exp = temp;}
		inline int getLevel() const {return level;}
		inline int getHealth() const {return health;}
		inline int getMana() const {return mana;}
		inline int getExp() const {return exp;}
	private:
		int level;
		int health;
		int mana;
		int exp;
		int maxExp;
	protected:
};

Character::Character(int defLevel, int defHealth, int defMana, int defExp, int defMaxExp):
	level(defLevel),
	health(defHealth),
	mana(defMana),
	exp(defExp),
	maxExp(defMaxExp)
{}

void Character::updateLevel()
{
	Character character;

	if(exp > maxExp)
		character.setLevel(level++);

	return;
}

void Character::dispStats()
{
	Character character;

	cout << level << endl;
	cout << health << "/" << health << endl;
	cout << mana << "/" << mana << endl;
	cout << exp << "/" << maxExp << endl;

	return;
}

void Character::loc(Character * tempAdd)
{
	cout << "\nInside loc function\n\n";
	
	tempAdd->dispStats();

	cout << endl;

	return;
}

int main()
{
	Character character(1, 50, 20, 0, 5);
	Character * charPtr = &character;

	charPtr->updateLevel();
	charPtr->dispStats();

	cout << "\nTesting Level Up..press any key to gain 10 exp";
	cin.get();

	charPtr->setExp(10);
	charPtr->updateLevel();
	charPtr->setExp(0);
	charPtr->loc(charPtr);
	charPtr->dispStats();
	charPtr = 0;

	return 0;
}
Of course when I call dispStats() inside loc() the variables
keep their data thanks to the pointer. I guess this is the
right way to use pointers but I am happy it compiled and
output like I wanted.
Scoody
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 65
Joined: Fri Feb 06, 2009 2:07 pm

Re: Confused on code

Post by Scoody »

zodiac976 wrote:I was messing around with that code again and I actually
got a pointer to work with it although I think a reference
would be better.

Code: Select all

#include <iostream>
using namespace std;

class Character
{
	public:
		Character() {};
		Character(int, int, int, int, int);
		void dispStats();
		void updateLevel();
		void loc(Character *);
//Accessors
		inline void setLevel(int temp) {level = temp;}
		inline void setHealth(int temp) {health = temp;}
		inline void setMana(int temp) {mana = temp;}
		inline void setExp(int temp) {exp = temp;}
		inline int getLevel() const {return level;}
		inline int getHealth() const {return health;}
		inline int getMana() const {return mana;}
		inline int getExp() const {return exp;}
	private:
		int level;
		int health;
		int mana;
		int exp;
		int maxExp;
	protected:
};

Character::Character(int defLevel, int defHealth, int defMana, int defExp, int defMaxExp):
	level(defLevel),
	health(defHealth),
	mana(defMana),
	exp(defExp),
	maxExp(defMaxExp)
{}

void Character::updateLevel()
{
	Character character;

	if(exp > maxExp)
		character.setLevel(level++);

	return;
}

void Character::dispStats()
{
	Character character;

	cout << level << endl;
	cout << health << "/" << health << endl;
	cout << mana << "/" << mana << endl;
	cout << exp << "/" << maxExp << endl;

	return;
}

void Character::loc(Character * tempAdd)
{
	cout << "\nInside loc function\n\n";
	
	tempAdd->dispStats();

	cout << endl;

	return;
}

int main()
{
	Character character(1, 50, 20, 0, 5);
	Character * charPtr = &character;

	charPtr->updateLevel();
	charPtr->dispStats();

	cout << "\nTesting Level Up..press any key to gain 10 exp";
	cin.get();

	charPtr->setExp(10);
	charPtr->updateLevel();
	charPtr->setExp(0);
	charPtr->loc(charPtr);
	charPtr->dispStats();
	charPtr = 0;

	return 0;
}
Of course when I call dispStats() inside loc() the variables
keep their data thanks to the pointer. I guess this is the
right way to use pointers but I am happy it compiled and
output like I wanted.
When you decalare Character character, you're making a new character, so in updateLevel you're just adjusting the level of the new character on the stack (which gets wiped when you leave that function). You can edit the variables directly inside the class' own function, the accessors are for those who want to do stuff to your object from outside (of course if you have some checking code then you'd be using the accessor). And "return" at the end of void-functions is unnecessary. This might work, just did some on-the-fly editing :)

Code: Select all

#include <iostream>
using namespace std;

class Character
{
	public:
		Character() {};
		Character(int, int, int, int, int);
		void dispStats();
		void updateLevel();
		void loc();
//Accessors
		inline void setLevel(int temp) {level = temp;}
		inline void setHealth(int temp) {health = temp;}
		inline void setMana(int temp) {mana = temp;}
		inline void setExp(int temp) {exp = temp;}
		inline int getLevel() const {return level;}
		inline int getHealth() const {return health;}
		inline int getMana() const {return mana;}
		inline int getExp() const {return exp;}
	private:
		int level;
		int health;
		int mana;
		int exp;
		int maxExp;
	protected:
};

Character::Character(int defLevel, int defHealth, int defMana, int defExp, int defMaxExp):
	level(defLevel),
	health(defHealth),
	mana(defMana),
	exp(defExp),
	maxExp(defMaxExp)
{}

void Character::updateLevel()
{
	if(exp > maxExp)
		level++;
}

void Character::dispStats()
{
	cout << level << endl;
	cout << health << "/" << health << endl;
	cout << mana << "/" << mana << endl;
	cout << exp << "/" << maxExp << endl;
}

void Character::loc()
{
	cout << "\nInside loc function\n\n";	
	dispStats();
	cout << endl;
}

int main()
{
	Character character(1, 50, 20, 0, 5);
	character.updateLevel();
	character.dispStats();

	cout << "\nTesting Level Up..press any key to gain 10 exp";
	cin.get();

	character.setExp(10);
	character.updateLevel();
	character.setExp(0);
	character.loc();
	character.dispStats();

	return 0;
}
User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

Re: Confused on code

Post by zodiac976 »

Scoody wrote:
zodiac976 wrote:I was messing around with that code again and I actually
got a pointer to work with it although I think a reference
would be better.

Code: Select all

#include <iostream>
using namespace std;

class Character
{
	public:
		Character() {};
		Character(int, int, int, int, int);
		void dispStats();
		void updateLevel();
		void loc(Character *);
//Accessors
		inline void setLevel(int temp) {level = temp;}
		inline void setHealth(int temp) {health = temp;}
		inline void setMana(int temp) {mana = temp;}
		inline void setExp(int temp) {exp = temp;}
		inline int getLevel() const {return level;}
		inline int getHealth() const {return health;}
		inline int getMana() const {return mana;}
		inline int getExp() const {return exp;}
	private:
		int level;
		int health;
		int mana;
		int exp;
		int maxExp;
	protected:
};

Character::Character(int defLevel, int defHealth, int defMana, int defExp, int defMaxExp):
	level(defLevel),
	health(defHealth),
	mana(defMana),
	exp(defExp),
	maxExp(defMaxExp)
{}

void Character::updateLevel()
{
	Character character;

	if(exp > maxExp)
		character.setLevel(level++);

	return;
}

void Character::dispStats()
{
	Character character;

	cout << level << endl;
	cout << health << "/" << health << endl;
	cout << mana << "/" << mana << endl;
	cout << exp << "/" << maxExp << endl;

	return;
}

void Character::loc(Character * tempAdd)
{
	cout << "\nInside loc function\n\n";
	
	tempAdd->dispStats();

	cout << endl;

	return;
}

int main()
{
	Character character(1, 50, 20, 0, 5);
	Character * charPtr = &character;

	charPtr->updateLevel();
	charPtr->dispStats();

	cout << "\nTesting Level Up..press any key to gain 10 exp";
	cin.get();

	charPtr->setExp(10);
	charPtr->updateLevel();
	charPtr->setExp(0);
	charPtr->loc(charPtr);
	charPtr->dispStats();
	charPtr = 0;

	return 0;
}
Of course when I call dispStats() inside loc() the variables
keep their data thanks to the pointer. I guess this is the
right way to use pointers but I am happy it compiled and
output like I wanted.
When you decalare Character character, you're making a new character, so in updateLevel you're just adjusting the level of the new character on the stack (which gets wiped when you leave that function). You can edit the variables directly inside the class' own function, the accessors are for those who want to do stuff to your object from outside (of course if you have some checking code then you'd be using the accessor). And "return" at the end of void-functions is unnecessary. This might work, just did some on-the-fly editing :)

Code: Select all

#include <iostream>
using namespace std;

class Character
{
	public:
		Character() {};
		Character(int, int, int, int, int);
		void dispStats();
		void updateLevel();
		void loc();
//Accessors
		inline void setLevel(int temp) {level = temp;}
		inline void setHealth(int temp) {health = temp;}
		inline void setMana(int temp) {mana = temp;}
		inline void setExp(int temp) {exp = temp;}
		inline int getLevel() const {return level;}
		inline int getHealth() const {return health;}
		inline int getMana() const {return mana;}
		inline int getExp() const {return exp;}
	private:
		int level;
		int health;
		int mana;
		int exp;
		int maxExp;
	protected:
};

Character::Character(int defLevel, int defHealth, int defMana, int defExp, int defMaxExp):
	level(defLevel),
	health(defHealth),
	mana(defMana),
	exp(defExp),
	maxExp(defMaxExp)
{}

void Character::updateLevel()
{
	if(exp > maxExp)
		level++;
}

void Character::dispStats()
{
	cout << level << endl;
	cout << health << "/" << health << endl;
	cout << mana << "/" << mana << endl;
	cout << exp << "/" << maxExp << endl;
}

void Character::loc()
{
	cout << "\nInside loc function\n\n";	
	dispStats();
	cout << endl;
}

int main()
{
	Character character(1, 50, 20, 0, 5);
	character.updateLevel();
	character.dispStats();

	cout << "\nTesting Level Up..press any key to gain 10 exp";
	cin.get();

	character.setExp(10);
	character.updateLevel();
	character.setExp(0);
	character.loc();
	character.dispStats();

	return 0;
}
Yea it is supposed to wipe the variable but when I return from
loc() the value of level incremented and kept the value.

output of variable level before updateLevel()
1
output after
2
output after returning from loc()
2

I use return even in a void function anyways in case I end up
changing the return value, it is just something I do -.-.

So you are saying I can directly change the values of the
classes variables without declaring an object of the class
and declaring an object of the class is for when you are
outside of that particular classes functions?
User avatar
dandymcgee
ES Beta Backer
ES Beta Backer
Posts: 4709
Joined: Tue Apr 29, 2008 3:24 pm
Current Project: https://github.com/dbechrd/RicoTech
Favorite Gaming Platforms: NES, Sega Genesis, PS2, PC
Programming Language of Choice: C
Location: San Francisco
Contact:

Re: Confused on code

Post by dandymcgee »

zodiac976 wrote: So you are saying I can directly change the values of the
classes variables without declaring an object of the class
and declaring an object of the class is for when you are
outside of that particular classes functions?
The reason for using accessors is so that you can expose private members to the rest of the program without allowing them to be directly edited. For altering variables within the class itself you simple set them like any other variable (ie. height = 5;). The whole point of "private" members is to either prevent them from being accessed from outside the class without going through the error-checking code of an accessor, or prevent them from being accessed from outside the class at all.

Here's a simple banking example I wrote up for you which uses accessors to prevent balance from being directly tampered with from outside of the class. Instead it checks to make sure there are sufficient funds when withdrawing money.

Account.h

Code: Select all

class Account{
    private:
        //User Data
        std::string firstName;
        std::string lastName;
        std::string alias;

        //Account Data
        int balance;
    public:
        //Constructor
        Account( std::string new_firstName, std::string new_lastName, std::string new_alias );

        //Balance Functions
        void Deposit( int amount );
        bool Withdraw( int amount );
};
Account.cpp

Code: Select all

//Create new account
Account::Account( std::string new_firstName, std::string new_lastName, std::string new_alias )
{
    firstName = new_firstName;
    lastName = new_lastName;
    alias = new_alias;
    balance = 0;
}

//Deposit money
void Account::Deposit( int amount )
{
    balance += amount;
}

//Withdraw money
//This demonstrates error-checking in an accessor
bool Account::Withdraw( int amount )
{
    if( amount > balance )
    {
        //Insufficient Funds!
        return false;
    }else{
        //Successful Withdrawal
        balance -= amount;
        return true;
    }
}
I hope this helps you understand the purpose of using accessors. ;)
Falco Girgis wrote:It is imperative that I can broadcast my narcissistic commit strings to the Twitter! Tweet Tweet, bitches! :twisted:
User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

Re: Confused on code

Post by zodiac976 »

Thanks that does help but does anyone know why
the data still remained in the variables after
returning from loc()?
User avatar
dandymcgee
ES Beta Backer
ES Beta Backer
Posts: 4709
Joined: Tue Apr 29, 2008 3:24 pm
Current Project: https://github.com/dbechrd/RicoTech
Favorite Gaming Platforms: NES, Sega Genesis, PS2, PC
Programming Language of Choice: C
Location: San Francisco
Contact:

Re: Confused on code

Post by dandymcgee »

Why are there "return;" calls in functions that you defined as "void" a.k.a. no return value?
Falco Girgis wrote:It is imperative that I can broadcast my narcissistic commit strings to the Twitter! Tweet Tweet, bitches! :twisted:
User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

Re: Confused on code

Post by zodiac976 »

dandymcgee wrote:Why is there a "return;" in dispStats which is defined as a function that has does not return a value "void"?
A habit I know it has no effect regardless unless I happen
to change the return type.
User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

Re: Confused on code

Post by zodiac976 »

I guess back to the main question that is bugging me
in this code below:

Code: Select all

#include <iostream>
using namespace std;

class Character
{
   public:
      Character() {};
      Character(int, int, int, int, int);
      void dispStats();
      void updateLevel();
      void loc(Character *);
//Accessors
      inline void setLevel(int temp) {level = temp;}
      inline void setHealth(int temp) {health = temp;}
      inline void setMana(int temp) {mana = temp;}
      inline void setExp(int temp) {exp = temp;}
      inline int getLevel() const {return level;}
      inline int getHealth() const {return health;}
      inline int getMana() const {return mana;}
      inline int getExp() const {return exp;}
   private:
      int level;
      int health;
      int mana;
      int exp;
      int maxExp;
   protected:
};

Character::Character(int defLevel, int defHealth, int defMana, int defExp, int defMaxExp):
   level(defLevel),
   health(defHealth),
   mana(defMana),
   exp(defExp),
   maxExp(defMaxExp)
{}

void Character::updateLevel()
{
   Character character;

   if(exp > maxExp)
      level++;

   return;
}

void Character::dispStats()
{
   Character character;

   cout << level << endl;
   cout << health << "/" << health << endl;
   cout << mana << "/" << mana << endl;
   cout << exp << "/" << maxExp << endl;

   return;
}

void Character::loc(Character * tempAdd)
{
   cout << "\nInside loc function\n\n";
   
   tempAdd->dispStats();

   cout << endl;

   return;
}

int main()
{
   Character character(1, 50, 20, 0, 5);
   Character * charPtr = &character;

   charPtr->updateLevel();
   charPtr->dispStats();

   cout << "\nTesting Level Up..press any key to gain 10 exp";
   cin.get();

   charPtr->setExp(10);
   charPtr->updateLevel();
   charPtr->setExp(0);
   charPtr->loc(charPtr);
   charPtr->dispStats();
   charPtr = 0;

   return 0;
}
Just wondering on the call to charPtr->loc(charPtr); why does
the values remain after returning from loc();? I was also just
messing around with pointers... :mrgreen:.
User avatar
dandymcgee
ES Beta Backer
ES Beta Backer
Posts: 4709
Joined: Tue Apr 29, 2008 3:24 pm
Current Project: https://github.com/dbechrd/RicoTech
Favorite Gaming Platforms: NES, Sega Genesis, PS2, PC
Programming Language of Choice: C
Location: San Francisco
Contact:

Re: Confused on code

Post by dandymcgee »

zodiac976 wrote: Just wondering on the call to charPtr->loc(charPtr); why does
the values remain after returning from loc();? I was also just
messing around with pointers... :mrgreen:.
I don't understand your question. Post JUST the relevant code (a smaller example), and tell us exactly what you EXPECT to happen and what IS happening.
Falco Girgis wrote:It is imperative that I can broadcast my narcissistic commit strings to the Twitter! Tweet Tweet, bitches! :twisted:
User avatar
zodiac976
Chaos Rift Regular
Chaos Rift Regular
Posts: 156
Joined: Thu Jun 18, 2009 10:03 am
Current Project: Booklet & Text RPG
Favorite Gaming Platforms: PC, PS3, PSP
Programming Language of Choice: C++
Location: AL
Contact:

Re: Confused on code

Post by zodiac976 »

dandymcgee wrote:
zodiac976 wrote: Just wondering on the call to charPtr->loc(charPtr); why does
the values remain after returning from loc();? I was also just
messing around with pointers... :mrgreen:.
I don't understand your question. Post JUST the relevant code (a smaller example), and tell us exactly what you EXPECT to happen and what IS happening.
Inside main()

Character character(1, 50, 20, 0, 5);
Character * charPtr = &character;

charPtr->updateLevel();
charPtr->dispStats();

cout << "\nTesting Level Up..press any key to gain 10 exp";
cin.get();

charPtr->setExp(10);
charPtr->updateLevel();
charPtr->setExp(0);
charPtr->loc(charPtr);<----------Right here after returning the variables should have been destroyed and
charPtr->dispStats();<----------this should display some wierd negative values but it keeps the values.
charPtr = 0;
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: Confused on code

Post by avansc »

why dont you just do Character pChar = new Character(params).
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
User avatar
dandymcgee
ES Beta Backer
ES Beta Backer
Posts: 4709
Joined: Tue Apr 29, 2008 3:24 pm
Current Project: https://github.com/dbechrd/RicoTech
Favorite Gaming Platforms: NES, Sega Genesis, PS2, PC
Programming Language of Choice: C
Location: San Francisco
Contact:

Re: Confused on code

Post by dandymcgee »

zodiac976 wrote: charPtr->loc(charPtr);<----------Right here after returning the variables should have been destroyed and
charPtr->dispStats();<----------this should display some wierd negative values but it keeps the values.
What? Why would they have been destroyed.. you are passing a pointer to itself to the class, which then calls it's own dispStats function, returns nothing, then calls dispStats again in main. There's no destruction whatsoever. Your loc function is the equivalent of:

Code: Select all

void Character::loc()
{
   cout << "\nInside loc function\n\n";

   this->dispStats();

   cout << endl;
}
"this" is a pointer to the class it is used in, and since you are passing a pointer to the Character class, to the Character class, it's the same as using the "this" keyword.

Again I don't see why you are expecting anything to be deleted..?
Falco Girgis wrote:It is imperative that I can broadcast my narcissistic commit strings to the Twitter! Tweet Tweet, bitches! :twisted:
Post Reply