I got stuck with creating a non-friend global function that has one parameter with pointer. In simple words I need a function that get passesd object via pointer, and write out all its members. So far I created a public declaration in MyClass
void WriteOutMyClass2 (MyClass *kp2);
And I created the function as well
void WriteOutMyClass2 (MyClass *kp2)
{
cout << "_a :" <<kp2._a <<endl;
}
but unfortunately I'm getting an error:
request for member ‘_a’ in ‘kp2’, which is of pointer type ‘MyClass*’ (maybe you meant to use ‘->’ ?)
I've pasted code at rexter.com, so you can look at that here. http://rextester.com/URTI56137
And additionally I'm attaching the whole code here.
class MyClass
{
private:
int _a;
int* c;
int size;
static int counter;
public:
friend void WriteOutMyClass1 (MyClass &kp1);
void WriteOutMyClass2 (MyClass *kp2);
MyClass() //default constructor
{
_a=0;
size = 10;
c = new int [size];
for(int i = 0; i<size; i++)
{
c[i] = 1;
}
counter++;
}
};
//Initialize friend fucntion
void WriteOutMyClass1 (MyClass &kp1)
{
cout << "_a :" <<kp1._a <<endl;
cout << "size :" <<kp1.size<<endl;
cout << "counter :" <<kp1.counter<<endl;
for(int i = 0; i<kp1.size; i++)
{
cout << "c[" << i << "] = " << kp1.c[i] << endl;
}
}
//Initialize non-friend global fucntion.
void WriteOutMyClass2 (MyClass *kp2)
{
cout << "_a :" <<kp2._a <<endl; // here I'm getting error.
}
int main()
{
}
edit:
What excatly I'm trying to do is, get access to private members of MyClass from non-firend function declared outside MyClass. Function shouldn't be static, and access to private members is needed via getter or not. I'm not aware of c++ possibilties. I appreciate any help!
ps: the "->" isn't enough, because the "_a" field is private. How would it looks with a getter?
edit2:
I unduerstand that some rules were broken but this code is an exercise I got from an university. It's specially done to show some approch. Unfortunatelly variable names are as they are, of course I could rename them but I forgot.