Hello I'm hoping someone might be able to help me with an issue that I'm currently facing with a program that I'm working on for a Uni assessment.
The question essentially asks for a class to be created whereby the data that is read in from within that class is used in class AND non-class functions providing output. I have successfully been able to complete this assessment with these functions in the class but unsuccessful in creating the functions in the driver program, however the requirements specifically require functions that are using the data from the class in separate non-class functions.
I'm not looking for anyone to complete this for me, but a previous example or a push in the right direction would be really appreciated.
so you want another function to acces something that is private in a class?
that is not possible! ofcourse i am joking.
as you said making variables public are kinda against oop methodology, and therefore they should be placed inside of the private part of the class.
you can acces them by using a getter function, wich is basicly a function inside the class that returns the variable you want, something like this:
1 2 3 4 5 6 7 8 9
class Class_name {
public:
get_a (){
return a;
}
private:
int a;
}
hope that helps :)
edit: i would like to add that the function name does not matter, but its nice to just call it get_ and then the variable name, so you know what the function does (in this case, gets variable a) ;)
Yes, it is possible. The solution would be to use friend functions. A friendclass or function is allowed to access the private and protected members of a class. To create a friend function, do the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class My_Class
{
private:
int A_;
public:
// Friend function:
friendint &A(My_Class &Instance);
};
// Defining the friend:
int &A(::My_Class &Instance)
{
return(Instance.A);
}
In the above code, only the global function ::A() can access the private members of ::My_Class.
Furthermore, even821's post is a possible solution, but is only useful it you're going to read a member, not write to it (his ::Class_name::get_a() function returns a copy of ::Class_name::a).
well i know my solution isnt the best,but its a simple way to acces information in a private class, also you can easily reverse my method to a setter function type thing, wehre instead of returning the variable you would overwrite it with a new value. so yes, i can set values as well, not only get.
but as i said its probably not the best method, but its a simple way to do it.