Reputation: 49
I have a class defined in header file as below:
// picture.hpp:
class Picture {
public:
int count;
void draw();
};
Corresponding implementing source file:
// picture.cpp
import "picture.hpp";
Picture::draw() {
// some code
someFunction();
}
void someFunction() {
//some code
// can I use variable "count" declared in Picture class in this function
}
Can someFunction() access members of Class Picture?
Upvotes: 0
Views: 1696
Reputation: 51
As your title says you want to access members of class from outside.There may be many ways out there. Like: making class member vaiable & function both static then call it without creating instances of class even if it is private.see-reference
But if you don't want to make member function static and use class member variable from outside,then you may use friend function.Now what friend function can do? you can read it from wikipedia or a blog or might be from here whatever suits your expectation.Now if you use friend function,you have to specify inside your class.like this
class Picture
{
public:
int count;
void draw(Picture obj);
friend void someFunction(/*other parameters if you have*/Picture obj); //as global friend
};
you can perform operations of your member variable inside somefunction() like this:
void someFunction(/*other parameters if you have*/ Picture obj)
{
//some code
// can I use variable "count" declared in Picture class in this function
printf("%d", obj.count);
return;
}
Here comes the design level problem. According to your code,you want to call somefunction() inside of your member function draw() but now somefunction() requires an object as parameter.So it can be done if you pass object in draw() member function.like this:
void Picture::draw(/*other parameters if you have*/ Picture objA)
{
// some code
someFunction(/*other parameters if you have*/ objA);
}
At last,call main function.like this:
int main()
{
Picture pic1;
pic1.draw(pic1);
return 0;
}
Now without creating instances you can not call outside the member of class(except static) [see reference] So,Here two things i have done,i have passed all parameter as 'pass by value' and made somefunction() as friend of that class. Now you have the option to ignore the above whole process as you declared count variable as public. So,use it anywhere inside your class member function just using instance & dot operator but if you desparate to use member variable outside of the class then above process might help you.
Let me know if it helps you or not.
Upvotes: 1