Ross Satchell Ross Satchell - 11 days ago 5x
C++ Question

Trying to use pointer to access private variable outside class, with member functions outside class

I'm trying to get my head around pointers so I have been reading and trying things.
Currently I'm trying to put member functions outside the class, but be able to access a private variable from inside the main function. From what I've read this can't be done, unless I have a pointer inside the class.
So I have tried putting a function that returns a pointer to my private variable inside the class, with all other member functions outside the class.
However when I try to read the private variable I run into compile problems.

I've tried reading other posts and trying their solutions, but I'm just getting more confused.
Ideally, I would like to have a member function named "area" outside the class that is passed a pointer to the private variable "radius" and returnss the area.

This is what I currently have:

#include <iostream>
#define PI 3.14159;
using namespace std;

class Circle{
float radius;
float *radPtr = &radius;
float getRadiusPtr(){
return *radPtr;
void getRadius();
void showRadius();
void Circle::getRadius() {
cout << "Enter Radius: "<< endl;
cin >> radius;

void Circle::showRadius(){
cout << "Radius: " << endl;

float Circle::area(*radPtr){
float ar;
float r = this.getRadiusPtr();
ar = PI * r * r;

int main(){
Circle c1;
cout << "Area: " << a << endl;

return 0;


You can't use &radius outside a member function, since there's no specific object whose radius member it should get the address of.

Furthermore, your getRadiusPtr() function isn't even returning a pointer. It's just returning the value of radius.


float *getRadiusPtr() {
    return &radius;

Then you can use it like:

int main() {
    Circle c1;
    float *r = c1.getRadiusPtr();
    float a = PI * *r * *r;
    cout << "Area: " << a << endl;
    return 0;