how can I use variable, which is set in one class in another? should it be private or public? Should I do that through reference? and if so, how? Thanks a lot for your answer.
Ok, so like this:
I have class A, where I have a varible a. My first question is: should this be variable private or public, if I want to use it in another class? or it doesnt matter?
1 2 3 4 5 6 7 8 9 10 11 12
class A
{
public:
int a;
private:
void f() {
int a = 10;
// do something else;
}
}
now I have a class B, where I want to use this variable in B::f1() from class A with the value, which was set in function f();
and here I got stuck. cos I dont know, how to use it. should I use some get_a function?
You have three options:
1- Make 'a' to be public, this way you'll can access it from anywhere outside the class 'A'
2- Make 'a' private/protected and write a public getter function
3- Make 'a' private/protected and class 'B' friend of class 'A', in this way only 'B' and 'A' could access A::a
could you explain that to me a bit more, please? i d like to know, how to use 'a' in B in options you gaved. cos I tried to use 'a' which is public in B and it return error. thanks a lot
If 'a' isn't a static member you need an object of 'A' to access it in 'B'
eg:
1 2 3 4 5 6 7 8 9
class A { public: int a; };
class B
{
void f1()
{
A obj;
std::cout << obj.a; // needs an object
}
};
1 2 3 4 5 6 7 8 9
class A { public: staticint a; };
int A::a = 10; // static members need to be defined
class B
{
void f1()
{
std::cout << A::a; // doesn't need an object
}
};
I think there are likely other semantic errors in your program, just based on what I'm seeing
there.
sizeof( mess ) on line 5 has constant value 4 (32-bit machine, 8 on 64-bit machine), since it is
asking how many bytes of memory are occupied by a pointer to (constant) character.
I think you are actually wanting the length of the C-string? In which case you'd use
strlen(), but seriously I'd considering moving to the more natural C++ STL types
std::string or std::vector.
Anyway, if you are going to use C-style strings, then a more appropriate type for a
would be size_t, not long int, since I don't know what it means to have a string of
length -42.