Reputation: 27216
Still trying to get back into C++ and fumbling on differences from Java.
Can anyone tell me what's wrong here?
#ifndef TEST_H
#define TEST_H
class Test {
public:
int x, y;
Test();
virtual ~Test();
protected:
private:
};
#endif // TEST_H
#include "Test.h"
Test::Test() {
x = 0;
y = 28;
}
Test::~Test()
{
//dtor
}
#ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "Test.h"
class testApp : public ofBaseApp{
public:
void setup();
[snip]
Test test_obj;
};
#endif
#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?
Upvotes: 1
Views: 191
Reputation: 11074
It should be either:
Test *test_obj;
//...
test_obj = new Test;
// ...
delete test_obj;
Or:
Test test_obj;
Then there's no need to release test_obj
since it's automatically done as soon as it gets out of scope.
Upvotes: 0
Reputation: 25537
Test *p = new Test();
Get into the habit of using auto_ptr or shared_ptr or unique_ptr rather than using raw pointers in C++.
Upvotes: 1
Reputation: 64283
To fix your error, this line :
Test test_obj;
should have been :
Test *test_obj;
Upvotes: 0
Reputation: 6315
In your test_app.h, you are declaring a Test object, not a pointer to a test object. Therefore in the constructor you do not need to create a new instance of Test on the heap. The error you are getting means that you are trying to assign a Test* to a variable of Test type.
Upvotes: 0
Reputation: 272772
new Test()
returns a Test *
, i.e. a pointer. You cannot assign this to a Test
object. You could do test_obj = Test();
, though.
Upvotes: 0
Reputation: 15576
You use new
with pointers in C++. It is different from Java.
Your declaration of Test test_obj
should be Test* test_obj;
However, you can declare variable simply on stack like Test test_obj;
. Doing this means that you don't have to new
the 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 delete
on the object to destroy it like this:
delete test_obj;
Remember, there is no automatic memory management in C++, therefore, you have to remember to delete
everything that you create with new
.
Upvotes: 8