Initialize superclass with subclass

Hi! I'm new to C++, but I have programmed a bit in Java before. I was wondering about polymorphism in C++. I know you can initialize a superclass with a subclass by typing:

1
2
3
4
Rectangle r;
Circle c;
Shape *s1 = &r;
Shape *s2 = &c;


But say we have a class called ShapeCollection, which has two Shape objects. What if we wanted to initialize these objects to Rectangles or Circles depending on what argument you passed to the constructor?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class ShapeCollection{
public:
    ShapeCollection(bool rectangles){
        if(rectangles){
            s1 = &Rectangle(); 
            s2 = &Rectangle();
        }else{
            s1 = &Circle(); 
            s2 = &Circle();
        }
    }
private:
    Shape *s1, *s2;
};


Why doesn't this work?
Rectangle() creates a temporary object that will be destroyed at the end of the line so you wouldn't want to store a pointer to it. You probably want to create the objects with new instead.

 
s1 = new Rectangle();
Topic archived. No new replies allowed.