First off I am new to C++, especially using C++ in an OOP fashion. I have a class with multiple subclasses, and I was wondering if I could ambiguously declare a variable to accept an object without limiting the which objects can be stored in it. I am asking because one of the multiple children will end up being used at a time. So if I cannot ambiguously declare a variable I a way to determine which of the numerous variables are in use.
Something along the lines of
obj randomObj = new className;
instead of
className randomObj = new className
You say you’re new to C++, and the syntax you use to describe what you want suggests you’re more familiar with another languages like Java or C#. The syntax you show works fine in those languages:
This works because, behind the scenes in Java and C#
myFooactually behaves as a pointer to a Foo rather than as name for a fixed memory region capable of storing a Foo. In C++ the syntaxFoo myFoocreates such a fixed memory region. Even if you try to put some derived type there by doing this:myFoocan still only hold a Foo object. Everything that’s not a Foo is ‘sliced’ away during the initialization ofmyFoo, because it just doesn’t fit in that fixed memory region..So in C++ you have to explicitly do what Java and C# do behind the scenes by using C++’s pointer syntax:
Now
myFoois a pointer to a Foo, and that pointer can refer to a anyFooobject, including the Foo parts of a DerivedFoo, without any slicing or anything occurring.new DerivedFoocreates a memory region where a DerivedFoo can exist, and thenmyFoois set to point at theFoopart of the createdDerivedFoo.