my_engine is declared inside Car and instantiated inside Car, or more accurately, it is instantiated within an instantiation of Car. Therefore, my_engine's scope is the same as the scope of the instance of Car. Car is instantiated in main(), therefore my_engine's scope in this case is main().
You would use B only if the constructed Engine instance needs to live beyond the lifetime of the Car instance that contains it.
(Having said that, there are times when pointers need to be used for other reasons, but I won't go into those. The bottom line is that pointers should be used only when you can't, for some reason (such as the lifetime issue), not use them).
One small correction/performance improvement to your code: Use initializer lists. Here is your constructor rewritten to use initializer lists:
1 2 3 4 5 6 7 8 9
|
class Car {
Engine my_engine;
public:
Car( int hp ) : my_engine( hp ) {
}
Engine get_engine() { return my_engine; }
};
| |
This is more efficient because the compiler will, unless you tell it otherwise, run the default constructor of every data member of Car prior to entering the body of Car's constructor. In your code, you then call the constructor of Engine a second time, and then call operator= on Engine to assign the newly constructed instance to my_engine, making a total of three function calls. In the above code, the syntax after the colon is how you tell the compiler to run a different constructor for your data members. In this case, I'm telling it to call Engine( int ) instead of Engine(), making only one function call.
Just one other thing to be aware of, if you aren't already: get_engine() returns a
copy of the Car's engine (ie, it run's Engine's copy constructor). Not sure if this is what you want. If you want the caller to be able to modify the Car's engine directly, you could return a reference. If you don't, you could return a const reference. In either case, returning a reference does not copy the Engine.