| | |
c++ beginner help
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
I'm learning c++ at the moment, and i just learnt about classes, so i decided to make a text game with a badguy and player class, and i was wondering how to refer to other classes variables(like this.health)
from other classes. and wether you have to create an instance of those classes like you do in python, heres my code:
And if you could tell me about any errors in this that would be appreciated
from other classes. and wether you have to create an instance of those classes like you do in python, heres my code:
c++ Syntax (Toggle Plain Text)
#include <cstdlib> #include <iostream> using namespace std; class Badguy { private: int this.health = 10, this.defense = 3; char this.name = "Orc"; int getAttributesInfo() { attributes [] = {this.health, this.defense, this.name}; return attributes; } } ; class Player { private: srand((1),(7)); int this.attack = rand(); char name = "Player"; int getDamage(void) { int Badguy.damage = this.attack - defense; if (Badguy.damage > Badguy.defense) { Badguy.health -= Badguy.damage; } } } ; int main() { }
And if you could tell me about any errors in this that would be appreciated
...
•
•
Join Date: Sep 2008
Posts: 83
Reputation:
Solved Threads: 15
I figure I ought to start off with in C++ with classes you can only declare variables not initialize them... Initializing them can be done via constructor.
Accessing other class variables either needs those variables to be declared public, or to be accessed by a public member function of the class you want the variables for.
Or you can declare a friend class or similar, excuse the somewhat poorly written example, it is messy but I'm hoping it gets the point across...
Take note that despite the constructor initializing testint to 123, because of Add_Attrib taking 2 reference parameters which 1 were testint, it changes the value to health instead... Just play around with the code & you'll soon see what you can do.
Although Assigning variables from another class means doing so in the bracket... Example...
Just the constructors, Push1 is a private member in class ref of type string, NewName is of type string in class example... You can see in the constructor there, that NewName is initialized inside the block this time.
Again Apologies for the poorly written example, I sort of just winged it quickly!
cpp Syntax (Toggle Plain Text)
class example { int testint; public: example(); int ret_val(){return testint;}; }; example::example():testint(123){}; //Constructor initializes testint to 123. You can also do initialization & all in the {} like a function. int main() { example obj; cout << "testint is: " << obj.ret_val() << "\n"; return 0; }
Accessing other class variables either needs those variables to be declared public, or to be accessed by a public member function of the class you want the variables for.
Or you can declare a friend class or similar, excuse the somewhat poorly written example, it is messy but I'm hoping it gets the point across...
cpp Syntax (Toggle Plain Text)
#include <cstdlib> #include <iostream> #include <string> using namespace std; class ref { int health; char undead; string Name; public: ref(); void Add_Attrib(int& x, char& y){ x = health; y = undead;}; friend class example; //class example is friend. }; class example { int testint; char testchar; ref obj; //creates object of ref. public: example(); int ret_val(){ obj.Add_Attrib(testint, testchar); cout << "Health is: " << testint << "\nUndead: " << testchar << "\n"; return testint;}; void friend_ex(){cout << "Enemy: " << obj.Name << endl;}; //example displays a private member of class ref without calling a member function of ref. }; example::example():testint(123){}; //Constructor initializes testint to 123. ref::ref():health(100), undead('y'), Name("Orc"){}; int main() { example obj; cout << "testint is: " << obj.ret_val() << "\n"; obj.friend_ex(); //uses object of class example to display private member of another class in this case class ref. return 0; }
Take note that despite the constructor initializing testint to 123, because of Add_Attrib taking 2 reference parameters which 1 were testint, it changes the value to health instead... Just play around with the code & you'll soon see what you can do.
Although Assigning variables from another class means doing so in the bracket... Example...
cpp Syntax (Toggle Plain Text)
example::example():testint(123){ NewName = obj.Push1;}; //Constructor initializes testint to 123. ref::ref():health(100), undead('y'), Name("Orc"),Push1("Test Example"){};
Just the constructors, Push1 is a private member in class ref of type string, NewName is of type string in class example... You can see in the constructor there, that NewName is initialized inside the block this time.
Again Apologies for the poorly written example, I sort of just winged it quickly!
•
•
Join Date: Sep 2008
Posts: 83
Reputation:
Solved Threads: 15
You'll learn more from trial & error when playing around with code yourself, having someone else write it for you won't strengthen your ability.
I've given you the necessary code for you to be able to correct your own code. I've told you that you can't initialize a variable in a class, instead you need to use the constructor. which should be declared public & be the same name of the class without a return type specified. (eg class Badguy constructor would be "public: Badguy();" without ")
I've also displayed multiple ways of accessing private members of other classes to which all it requires from you now, is to use the code I shown you to try stuff out & learn from it, to which you will then be able to apply it to your own needs much better than if someone re-writes your actual program for you.
Last but not least, Google is your friend, need more examples... Google up tutorials on classes & friend classes/friend functions.
I've given you the necessary code for you to be able to correct your own code. I've told you that you can't initialize a variable in a class, instead you need to use the constructor. which should be declared public & be the same name of the class without a return type specified. (eg class Badguy constructor would be "public: Badguy();" without ")
I've also displayed multiple ways of accessing private members of other classes to which all it requires from you now, is to use the code I shown you to try stuff out & learn from it, to which you will then be able to apply it to your own needs much better than if someone re-writes your actual program for you.
Last but not least, Google is your friend, need more examples... Google up tutorials on classes & friend classes/friend functions.
•
•
•
•
You'll learn more from trial & error when playing around with code yourself, having someone else write it for you won't strengthen your ability.
I've given you the necessary code for you to be able to correct your own code. I've told you that you can't initialize a variable in a class, instead you need to use the constructor. which should be declared public & be the same name of the class without a return type specified. (eg class Badguy constructor would be "public: Badguy();" without ")
I've also displayed multiple ways of accessing private members of other classes to which all it requires from you now, is to use the code I shown you to try stuff out & learn from it, to which you will then be able to apply it to your own needs much better than if someone re-writes your actual program for you.
Last but not least, Google is your friend, need more examples... Google up tutorials on classes & friend classes/friend functions.
cpp Syntax (Toggle Plain Text)
class Badguy { private: int attributes [] = {int health, int defense, char name}; public: badguy(); int ret_val(){return attributes;}; }; class Player { private: int attributes[] = {char name, int attack}; public: player(); int ret_val(){return attributes;}; int attack() { } }; Badguy::badguy()::attributes(){health, defense, name}; Player::Player()::attributes(){name, attack};
...
•
•
Join Date: Dec 2008
Posts: 17
Reputation:
Solved Threads: 2
C++ Syntax (Toggle Plain Text)
int this.health = 10, this.defense = 3; char this.name = "Orc";
C++ Syntax (Toggle Plain Text)
int getAttributesInfo() { attributes [] = {this.health, this.defense, this.name}; return attributes; }
•
•
Join Date: Sep 2008
Posts: 83
Reputation:
Solved Threads: 15
•
•
•
•
Would this work:
cpp Syntax (Toggle Plain Text)
class Badguy { private: int attributes [] = {int health, int defense, char name}; public: badguy(); int ret_val(){return attributes;}; }; class Player { private: int attributes[] = {char name, int attack}; public: player(); int ret_val(){return attributes;}; int attack() { } }; Badguy::badguy()::attributes(){health, defense, name}; Player::Player()::attributes(){name, attack};
Elements of an array are the same type as the array, that is an int array only holds ints & they don't have different names, in the case of
int attributes [] = {int health, int defense, char name};
it's an invalid definition of an array & don't forget you can't initialize in a class anyway, I'd honestly vouch for taking the easier route & getting rid of attributes... Just declare
int health, defence;
string name;
instead or something similar.
You almost got the constructor call right, badguy(); is case sensetive to the class name, that is
cpp Syntax (Toggle Plain Text)
class BadGuy { public: Badguy(); }
is different than
cpp Syntax (Toggle Plain Text)
class BadGuy { public: BaDGuY(); }
to which both are invalid... On line 4: BadGuy(); would be correct however!

cpp Syntax (Toggle Plain Text)
Badguy::badguy()::attributes(){health, defense, name}; Player::Player()::attributes(){name, attack};
Style is, Class::Constructor():Variable(Value){};
Notice that after Constructor there is only 1 colon, the :: is a scope operator, which isn't what is wanted. Inside the blocks you can also do initialization... Example
Badguy::Badguy():health(100){};
is the same as
Badguy::Badguy(){health = 100;};
Both of those initialize health to 100.
Assume you declare int health, defence; in the Badguy class then an initializer like so would work...
Badguy::Badguy(){health = 100; defence = 100;};
Both health & defence in the class would then be 100. Try compiling the code yourself to see if it works.
•
•
•
•
Have you tried compiling it & seeing for yourself? The short answer would be no & there are quite a few reasons why & since it's late & I'm tired I'll go through it quickly...
Elements of an array are the same type as the array, that is an int array only holds ints & they don't have different names, in the case of
int attributes [] = {int health, int defense, char name};
it's an invalid definition of an array & don't forget you can't initialize in a class anyway, I'd honestly vouch for taking the easier route & getting rid of attributes... Just declare
int health, defence;
string name;
instead or something similar.
You almost got the constructor call right, badguy(); is case sensetive to the class name, that is
cpp Syntax (Toggle Plain Text)
class BadGuy { public: Badguy(); }
is different than
cpp Syntax (Toggle Plain Text)
class BadGuy { public: BaDGuY(); }
to which both are invalid... On line 4: BadGuy(); would be correct however!
cpp Syntax (Toggle Plain Text)
Badguy::badguy()::attributes(){health, defense, name}; Player::Player()::attributes(){name, attack};
Style is, Class::Constructor():Variable(Value){};
Notice that after Constructor there is only 1 colon, the :: is a scope operator, which isn't what is wanted. Inside the blocks you can also do initialization... Example
Badguy::Badguy():health(100){};
is the same as
Badguy::Badguy(){health = 100;};
Both of those initialize health to 100.
Assume you declare int health, defence; in the Badguy class then an initializer like so would work...
Badguy::Badguy(){health = 100; defence = 100;};
Both health & defence in the class would then be 100. Try compiling the code yourself to see if it works.
I suggest you to have a good understanding of following features from C and C++ before you begin writing good classes.
C
datatypes
Arrays
character strings and string functions.
Structures
Functions
C++
class & object
bool datatype
constructor
destructor
functions in C++
default arguments to function parameters
this pointer
reference variable
---------------------
http://www.cplusplus.com/doc/tutorial/
should be good to start at.
I did it, Thanks for all your help, heres my code if you want to see:
c++ Syntax (Toggle Plain Text)
#include <iostream> using namespace std; class Badguy { private: int health, defense; char name; public: Badguy(); int ret_val(){return health, defense, name;}; }; class Player { private: char name; int attack; public: Player(); int ret_val(){return name, attack;}; }; Badguy::Badguy(){ health = 100; defense = 3; }; Player::Player(){ name = 'Tom'; attack = 5; }; int main() { Player p; Badguy b; cin.get(); }
...
![]() |
Similar Threads
- What program language should a beginner use? (IT Professionals' Lounge)
- C++ Beginner - #include recursion problem (C++)
- MS Access Beginner (MS SQL)
- PHP Beginner Here (PHP)
- beginner (C++)
- Beginner's questions: C++ and databases (C++)
- beginner needs help with game programming (Game Development)
Other Threads in the C++ Forum
- Previous Thread: How to return pointer to object & avoid memory leak?
- Next Thread: How do I make vectors of an already vectorized thing?
| Thread Tools | Search this Thread |
api array arrays beginner binary bitmap c++ c/c++ calculator char class classes code compile compiler console conversion convert count data database delete desktop developer directshow dll download dynamic encryption error file forms fstream function functions game generator getline givemetehcodez google graph gui homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux loop looping loops map math matrix memory multiple news node number output parameter pointer problem program programming project proxy python random read recursion recursive return string strings struct temperature template templates test text text-file tree unix url variable vector video visualstudio win32 windows winsock word wordfrequency wxwidgets





