I am new to object oriented programming and am having a difficult time trying to figure out how to pass a public variable to another class. I have the #include"filename.h" on the class trying to access the variable from the first class. This variable is just an int set to a number. Any help is appreciated.
assuming public variables in both classes, here are some suggestions about passing static and non-static variables from class A to class B. you can have other scenarios based on combinations of public and private access in each class:
#include <iostream>
class A
{
public:
staticint staticVar;//not attached to an instance of A
int nonStaticVar;//always comes attached to an instance of A
};
int A::staticVar = 42;
class B
{
public:
int b_staticVar = 0;
int b_nonStaticVar = 0;
};
int main()
{
B b;
b.b_staticVar = A::staticVar;
std::cout << b.b_staticVar << "\n";//prints 42;
std::cout << b.b_nonStaticVar << "\n";//prints 0 (default value)
A a;
a.nonStaticVar = 24;
b.b_nonStaticVar = a.nonStaticVar;
std::cout << b.b_nonStaticVar << "\n";//prints 24
}
the other thing that you might also wish to look up on to see if that meets your requirements is classes having objects of other class(es) as its data members - this is known as containment or composition - http://www.learncpp.com/cpp-tutorial/102-composition/