Create pointer to object on the heap

Hi everyone,

I am struggling to create a pointer to an object on the heap and access its methods outside of the function in which I declared it. In App.h, I created an instance of the class “Ball”, whose methods I can access perfectly fine in setup(), update(), and draw().

App.h

#pragma once

#include "ofMain.h"
#include "Ball.hpp"

class ofApp : public ofBaseApp{

	public:
		void setup();
		void update();
		void draw();
		void mousePressed(int x, int y, int button);
    
        Ball myBall;
    
};

App.cpp

#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    
    ofBackground(ofColor::white);
    
    myBall.setup();
    
}

//--------------------------------------------------------------
void ofApp::update(){

    myBall.update();
    myBall.jiggle();
    
}

//--------------------------------------------------------------
void ofApp::draw(){
    
    myBall.draw();
    
}

In mousePressed(), I am trying to create a pointer to the object “Ball” on the heap, which seems to work fine:

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

    Ball * secondBall = new Ball();
}

However, when I try to call the methods of “secondBall” outside of mousePressed(), I get an error message (Member Reference Type).

App.cpp

#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    
    ofBackground(ofColor::white);
    
    myBall.setup();
    
    secondBall->setup();
    
}

//--------------------------------------------------------------
void ofApp::update(){

    myBall.update();
    myBall.jiggle();
    
    secondBall->update();
    secondBall->jiggle();
    
}

//--------------------------------------------------------------
void ofApp::draw(){
    
    myBall.draw();
    
    secondBall->draw();

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

    Ball * secondBall = new Ball();
}

I am not sure why I get this error, as I have learned that the “new” keyword would make a variable globally accessible. If anyone can help me out with this, I would appreciate it!

Thank you!

Hi.
secondBall is created in the heap, but the variable is local to mousePressed, so it cannot be referenced outside.
See here for a long (but necessary) explanation: https://openframeworks.cc/ofBook/chapters/memory.html