For example, in the main function, I want to get the user's input. Depending on the input, I will create either a Rectangle
or a Circle
, which are child classes of Object
. If there's no input (or unknown), then I will just create a generic object.
class Object
{
public:
Object();
void Draw();
private:
....
};
class Rectangle:public Object
{
public:
Rectangle();
.... //it might have some additional functions
private:
....
};
class Circle:public Object
{
public:
Circle();
.... //it might have some additional functions
private:
....
};
main function:
string objType;
getline(cin, objType);
if (!objType.compare("Rectangle"))
Rectangle obj;
else if (!objType.compare("Circle"))
Circle obj;
else
Object obj;
obj.Draw();
Of course, the code above won't work because I can't instantiate an object inside an If statement. So i tried something like this.
Object obj;
if (!objType.compare("Rectangle"))
obj = Rectangle();
else if (!objType.compare("Circle"))
obj = Circle();
obj.Draw();
This code would compile, but it won't do what I want. For some reason, the object was not initiated the way the child class should (for example, I set the some Object's member variables, specifically, a vector, differently in the child classes). However, when I put a break point at the Child class constructor, it did run through there.
So how should I put instantiate Objects as its child classes in some if-statements??
You can create automatic objects in
if
statements, but they will be destroyed at the end of the scope they are created in so they don't work for this problem.The reason you can't do the
obj = Rectangle()
one is because of slicing.You have to have a pointer to an
Object
. Pointers to base objects can also point to instances of child objects. Then you can dynamically create the object inside theif
withnew
(objects created withnew
disregard scope and are only destroyed when you calldelete
on a pointer to them), thendelete
it when you're done:Alternatively, you can use smart pointers and then you don't have to worry about manually deallocating the object: