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.
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...
#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...
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! :)