Meroon
Meroon

Reputation: 3488

Store object as pointer in class in C++

I'm learning C++ right now and I wanted to get a little advice on storing member variable objects. I want to store an instance of B in A, what is the best way to do this?

[EDIT] - I made the example more real world. I need to be able to construct and assign a texture at runtime and assign it to a game object.

class GameObject
{
public:
    Texture texture;
};

....

GameObject gameObject;
Texture texture;

gameObject.texture = texture;

or

class GameObject
{
public:
    Texture *texture;
};

....

GameObject gameObject;

gameObject.texture = new Texture;

I'm trying not to use pointers, but in some instances I feel I need to.

Upvotes: 1

Views: 1801

Answers (4)

nobsid
nobsid

Reputation: 186

It depends on if you want A to control the memory of B.

Using pointers is very useful when passing objects back and forth between other objects. When you decide not to use pointers it is important to realize that as soon as an object goes out of scope, so do its member variables. Which can lead to problems if pointers to that object's members still exist elsewhere.

If this won't be an issue in your application I would avoid using pointers.

Upvotes: 0

Shmuel A. Kam
Shmuel A. Kam

Reputation: 84

Here are what I think are good criteria to use:

  1. Function: Is B PART of A or just related to it? A Car has an Engine, but the Driver is external. Another way to look at this is: Are they together from the start or is B assigned / given to A?

  2. Construction: Is B fully known/definable at the time that A is constructed?

Upvotes: 0

Zeenobit
Zeenobit

Reputation: 5194

It really depends on your particular solution and need. Both ways are just fine and acceptable. There is no "right way" to do most things in any language because your solution dictates how things should be done.

Though one thing to keep in mind is that if B is a large class with many data members, it would increase the size of A if you don't use pointers. Also, if you do use pointers, you need to make sure proper allocation and de-allocation is performed and not trust the user with doing that.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206526

If you want to reseat(refer to different class B objects) your member variable to different objects use a pointer. If not just use an object.

Yes, it is a good idea to avoid pointers and if at you need to use them prefer smart pointers instead of raw/naked pointers.

Upvotes: 3

Related Questions