#include<iostream>
using namespace std;
class item{
int a,b;
void getdata(int x,int y){
x=a;
y=b;
}
public:
void here(int a,int b)
{
void getdata();
}
void display();
};
void display()
{
printf("a is %d",a);
printf("\nb is %d ",b);
}
int main()
{
item A;
A.here(10,20);
A.display();
}
Errors
a and b are not declared in this scope for display function.
I cant also acces private function i.e void getdata(int,int) with a object without a public method, Right???
>Solution :
You’ve implemented a free function called display. The declared member function display does not have an implementation.
It should be:
void item::display() {
std::printf("a is %d\n", a);
std::printf("b is %d\n", b);
}
You should also #include <cstdio> to use std::printf.
Also note that the getdata function doesn’t actually get any data since it assigns values to the local variables x and y. If you want the values available at the call-site, take x and y by reference:
void getdata(int& x, int& y) { // note the &
x=a;
y=b;
}
It also doesn’t make sense to have getdata private. Instances of item can access the member variables directly so getdata is pointless unless made protected or public. You most probably want to have it public.
Since neither display nor getdata changes the object, you should also make them const qualified so that they can be used in const contexts.
The here function doesn’t make sense since it calls getdata without arguments. I assume you want to assign values to the member variables a and b. If so:
void here(int a, int b) {
this->a = a;
this->b = b;
}