I’m used to doing Java programming, where you never really have to think about pointers when programming. However, at the moment I’m writing a program in C++. When making classes that have members of other classes, when should I use pointers and when should I not? For example, when would I want to do this:
class Foo { Bar b; }
As opposed to this:
class Foo { Bar* b; }
Start by avoiding pointers.
Use them when:
Barinstance is actually managed by some other part of your program, whereas theFooclass just needs to be able to access it.Barobject (i.e., you want to create it after constructingFoo).Barobject may not exist at all; you would usenullalso in Java. However, check out boost::optional as well.Baris actually a base class, and you need the instance to be polymorphic.In any of these cases (*), start by using a smart pointer, such as boost::shared_ptr. Otherwise, you are likely to forget to deallocate the memory, sooner or later. Once you know what you are doing, consider case-by-case what pointer type is best.
(*) any case – except, probably, the bullet regarding GUI widgets; in this case, your toolkit would most probably manage the resources for you as well