I am moving on to C ++ with Java, and I am having trouble understanding the basics of C ++ classes and the best methods for designing them. In particular, I am wondering if I should use a pointer to my class member in the following case.
I have a custom class Foo that represents the state of a game at a particular turn, and Foo has a member variable in the user line of the class, which is a logical subset of this state of the game. For example, Foo represents a chessboard, and Bar represents objects under attack and their shoots (not my specific case, but a more universal analogy, I think).
I would like to find the sequence of steps by copying Foo and accordingly updating the state of the copy. When I finish searching for this sequence of movements, I will drop this copy and still have my original Foo representing the current state of the game.
In Foo.h, I declare my Foo class, and I declare a member variable of type Bar:
class Foo { Bar b; public: Foo(); Foo(const Foo& f); }
But in the implementation of my Foo constructors, I call the Bar constructor with some arguments specific to the current state that I will know at runtime. As I understand it, this means that the constructor of Bar is called twice - once, because I wrote "Bar b"; above (which calls the default constructor, if I understand correctly), and once, because I write something like "b = Bar (arg1, arg2, ...)" in Foo :: Foo () and Foo: : Foo (const Foo & amp f).
If I try to make as many copies of Foo per second as possible, this is a problem, right?
I think a simple solution is to declare a pointer to Bar instead: "Bar * b", which should avoid instantiating b twice. Is this a good practice? Does this mean any pitfalls I should know about? Is there a better solution? I canβt find a specific example to help me (besides a lot of warnings against using pointers), and all the information about class design is really overwhelming, so any guidance would be greatly appreciated!
EDIT: Yes, I will have all the information needed to create a Bar when I create my Foo. I think everyone brought this out, but to be clear, I have something similar already for my default constructor:
Foo(int k=5);
and in foo.cpp:
Foo::Foo(int k) { b = Bar(k); ... }
and then my Foo and his Bar member are updated gradually as the state of the game changes.
So calling my custom constructor bar on my list of constructor constructor foo Looks like the best way to do this. Thanks for answers!