"class::data member is private" error, but I'm operating on it with a member function?

nmar picture nmar · Sep 30, 2012 · Viewed 13.8k times · Source

I'm fairly new to C++, and I don't understand what is triggering this error:

/home/---/Documents/C++/---_lab2/lab2c.cpp||In function ‘int main()’:|
Line 9: error: ‘float circle::x1’ is private
Line 58: error: within this context

I know the data member x1 (x2,y1,y2 as well) is private, but I am operating on the object myObj using functions that are members of the class circle, so shouldn't they still work? Can someone explain to me what's wrong here?

#include <iostream>
#include <cmath>
#define PI 3.14159

using namespace std;

class circle{

private:
float x1,y1,x2,y2;

protected:

float distance(float x1,float y1,float x2, float y2){
    return sqrt(fabs((x2-x1)*(x2-x1))+fabs((y2-y1)*(y2-y1)));
};

public:

float radius(float x1, float y1, float x2, float y2){
    float rad = distance(x1,y1,x2,y2);
    return rad;
};

float circumference(float rad){
    return 2*PI*rad;
};

float area(float rad){
    return PI*rad*rad;
};

float populate_classobj(float x1main,float x2main,float y1main,float y2main){
x1 = x1main;
x2 = x2main;
y1 = y1main;
y2 = y2main;
};

};

int main(){

circle myObj;
float x1main,x2main,y1main,y2main;
cout << "Coordinates of center" << endl;
cout << "X: ";
cin >> x1main;
cout << "Y: ";
cin >> y1main;
cout << "Coordinates of point on circle" << endl;
cout << "X: ";
cin >> x2main;
cout << "Y: ";
cin >> y2main;

myObj.populate_classobj(x1main,x2main,y1main,y2main);

cout << "Radius is " << myObj.radius(myObj.x1,myObj.y1,myObj.x2,myObj.y2) << endl;
cout << "Circumference is " << myObj.circumference(myObj.radius(myObj.x1,myObj.y1,myObj.x2,myObj.y2)) << endl;;
cout << "Area is " << myObj.area(myObj.radius(myObj.x1,myObj.y1,myObj.x2,myObj.y2)) << endl;



return 0;
}

Answer

Luchian Grigore picture Luchian Grigore · Sep 30, 2012

You're attempting to access private members outside the class when you call radius & other methods.

But your real problem is with the logic. Why do you need to pass parameters to, for example, the radius method of your class:

float radius(float x1, float y1, float x2, float y2){
    float rad = distance(x1,y1,x2,y2);
    return rad;
};

The circle is already self-contained, why not just:

float radius(){
    float rad = distance(x1,y1,x2,y2);
    return rad;
};

Same with:

float circumference(){
    return 2*PI*radius();
};

float area(){
    return PI*radius()*radius();
};

Also, note that:

circle myObj;

creates an invalid object. You shouldn't have to call populate_classobj just to make it valid. Instead, have a proper constructor:

circle(float x1main,float x2main,float y1main,float y2main) :
x1(x1main),
x2(x2main),
y1(y1main),
y2(y2main)
{
};

and create the object as:

circle myObj(x1main,x2main,y1main,y2main);