Casting

I have a question at this program:

/*1*/ #include <iostream>
/*2*/ using namespace std;

/*3*/ class A{
/*4*/ public:
/*5*/ virtual void print() { cout << "A ";}
/*6*/ };

/*7*/ class B: public A{
/*8*/ public:
/*9*/ void print() { cout << "B ";}
/*10*/ };

/*11*/ class C {
/*12*/ public:
/*13*/ void print() { cout << "C ";}
/*14*/ };

/*15*/ class D :public C{
/*16*/ public :
/*17*/ void print() { cout << "D "; }
/*18*/ };

/*19*/ int main () {
/*20*/ A **arr1 = new A*[3];
/*21*/ C ** arr2 = new C*[3] ;

/*22*/ arr1[0] = new A();
/*23*/ arr1[1] = new B();

/*24*/ arr2[0] = new C();
/*25*/ arr2[0] = new D();

/*26*/ arr1[0]->print();
/*27*/ arr1[1]->print();
/*28*/ arr2[2]->print();
/*29*/ arr2[3]->print(); //print 'C'

/*30*/ ((A *) arr1[0])->print();
/*31*/ ((B *) arr1[1])->print();
/*32*/ ((C *) arr2[2])->print();
/*33*/ ((D *) arr2[3])->print() ; // print 'D'

/*34*/ return 0;
/*35*/ }


Questions:

1)Line 29: The array defined to be at lenght of (3) (see line 21) - How we can acsses to "arr2[3]"?

2) Line 33: arr2 recived an addresses of class "C"- How he recive an accsees to the function of Class "D". I mean: object from the type of 'C' do not recognize a functions from the 'Sun' that inherted him. (but the opposite it surely true).
In C and C++, indexes start at zero. So given:
 
C** arr2 = new C*[3];

The valid index values are 0, 1, 2.

Don't use C style casts in C++ as they can be ambiguous. Instead use one of static_cast, const_cast, reinterpret_cast or dynamic_cast.
Use code tags and we won't have to manually add the line numbers.

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
36
37
38
39
40
41
42
43
44
45
#include <iostream>
using namespace std;

class A{
    public:
    virtual void print() { cout << "A ";}
};

class B: public A{
    public:
    void print()	{ cout << "B ";}
};

class C {
    public:
    void print() { cout << "C ";}
};

class D :public C{
    public :
    void print() { cout << "D "; }
};

int main () {
    A **arr1 = new A*[3];
    C ** arr2 = new C*[3] ;

    arr1[0] = new A();
    arr1[1] = new B();

    arr2[0] = new C();
    arr2[0] = new D();

    arr1[0]->print();
    arr1[1]->print();
    arr2[2]->print();
    arr2[3]->print(); //print 'C'

    ((A *) arr1[0])->print();
    ((B *) arr1[1])->print();
    ((C *) arr2[2])->print();
    ((D *) arr2[3])->print() ; // print 'D'

    return 0;
}

See: http://www.cplusplus.com/articles/jEywvCM9/
Thank you, JLBorges.
Topic archived. No new replies allowed.