Reputation: 7024
I'm working on some C++11 examples, but i'm a little rusty. I'm trying to add an object instance to a class attribute. I have something like this:
Entity.h
class Entity {
private:
MyClass object;
public:
Entity();
void doTest();
};
Entity.cpp
#include "Entity.h"
Entity::Entity() {
}
void Entity::doTest(stuff) {
object = new MyClass(stuff);
}
Is this correct? How can i do this in C++?
Upvotes: 0
Views: 215
Reputation: 2056
You want to use in the decleration:
MyClass* object
Also, if you are going to use new MyClass
make sure you use delete object
to avoid leaks.
i.e.
Entity::Entity() { object = NULL; } //constructor
Entity::doTest(stuff) {
delete object;
object = new MyClass(stuff);
}
//Following rule of three, since we need to manage the resources properly
//you should define Copy Constructor, Copy Assignment Operator, and destructor.
Entity::Entity(const Entity& that) { //copy constructor
object = that.object;
//assumes you've correctly implemented an assignment operator overload for MyClass
}
//invoke copy and swap idiom* if you wish, I'm too lazy
Entity& Entity::operator=(const Entity& source) {
MyClass* temp = new MyClass(source.object)
//assumes you've correctly implemented an copy constructor (or default one works) for MyClass.
delete object;
object = temp;
return *this;
}
Entity::~Entity() { //destuctor
delete object;
}
You should avoid dynamic allocation if it is at all possible. You should also use smart pointers (like std::shared_ptr
) but if you do wish to use raw pointers, then abide by the rule of three.
Upvotes: 0
Reputation: 36401
In C++ your object
field is really an object. That means that there is an allocated memory inside every Entity
object you may create. The problem is how you can initialize that object
field ?
MyClass
has no ctor or a ctor callable with no parameter, everything is ok.if not, you should define the initialization of the field at the same time you define the ctor of Entity
this way
Entity::Entity() : object(parameters) {
code for Entities initialization
}
this is a way to ensure the correctness of your initialization so that object
is initialized before you have control on the initialization of the Entity
.
Your object
is statically initialized inside each Entity
, this is a good way, in C++, to code what is called a composition in object oriented programming.
Upvotes: 0
Reputation: 254501
It's all correct apart from the new
. Only use that when you need dynamic allocation; in this case, you just want to create an object:
object = MyClass(stuff);
Or perhaps you want to initialise it in the constructor instead:
Entity(stuff) : object(stuff) {}
Upvotes: 2
Reputation: 11047
It is wrong. object
is an object not a pointer. but your code
object = new MyClass(stuff);
treat object
as a pointer.
You can either declare object
as a pointer in the class Entity
or change your function doTest
;
If you want a pointer it is better to use smart pointers
in C++, such as unique_ptr
.
Upvotes: 0