Help with base pointers

Could any show me how to code a for loop that assigns a base pointers to a series of already initialized derived objects. I don't know where to even start with this.

This is what I have so far. How do I get the assignment to point to the correct derived class or am I thinking about this incorrectly?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include "shape.h"
#include "rectangle.h"
#include "circle.h"
#include "square.h"
#include "triangle.h"

int main()
{

    Rectangle r(15,15, Red, 5, 10);
    Circle c(30,30, Blue, 5);
    Circle cTwo(50, 30, Violet, 10);
    Square s(0, 0, Green, 7);
    Triangle t(50, 50, Indigo, 5, 10);

    int n = 5;


    Shape* sptrs[] = {new Rectangle, new Circle, new Square, new Triangle}


   for (int i = 0; i >= n; ++i)
    {

       // ??

    }




    return 0;

}
Last edited on
I can hardly understand what you are talking about..
Do you want Shape* sptrs[] = { &r, &c, &s, &t };?
Note that then to make use of the classes, you need virtual functions.
Also:
1
2
3
4
5
6
7
8
9
10
11
12
int n = 5; // oops
int n = 4;

// ...

//for (int i = 0; i >= n; ++i) // oops
for (int i = 0; i < n; ++i)
{

    sptrs[i]->func(); // call them like this

}

Topic archived. No new replies allowed.