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!