Still trying to get back into C++ and fumbling on differences from Java.
Can anyone tell me what’s wrong here?
Test.h
#ifndef TEST_H
#define TEST_H
class Test {
public:
int x, y;
Test();
virtual ~Test();
protected:
private:
};
#endif // TEST_H
Test.cpp
#include "Test.h"
Test::Test() {
x = 0;
y = 28;
}
Test::~Test()
{
//dtor
}
My main app header (I’m using openFrameworks)
#ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "Test.h"
class testApp : public ofBaseApp{
public:
void setup();
[snip]
Test test_obj;
};
#endif
test_app.cpp
#include "testApp.h"
#include "Test.h"
//--------------------------------------------------------------
void testApp::setup(){
test_obj = new Test();
}
[snip]
This should be straightforward, right? Define a class Test, declare a variable of class Test (test_obj) in test_app.h and then create an instance and assign it to that variable in the test_app.cpp file.
However I’m getting this error message from the compiler in the assignment line :
error: no match for ‘operator=’ in ‘((testApp*)this)->testApp::test_obj = (operator new(12u), (<statement>, ((Test*)<anonymous>)))’
What am I doing wrong? What am I not understanding here?
You use
newwith pointers in C++. It is different from Java.Your declaration of
Test test_objshould beTest* test_obj;However, you can declare variable simply on stack like
Test test_obj;. Doing this means that you don’t have tonewthe object, the constructor is automatically called and hence, object is initialized.To expand on it a little bit more:
There are two ways of object creation in C++.
First one creates an object on the stack and it is automatically destroyed (destructor is called) when object goes out of scope.
For the second one, the object is created on heap and you have to explicitly call
deleteon the object to destroy it like this:Remember, there is no automatic memory management in C++, therefore, you have to remember to
deleteeverything that you create withnew.