// ----------------
// ObjectArrays.c++
// ----------------
#include <cassert> // assert
#include <iostream> // cout, endl
#include <vector> // vector
struct A {int i; void f () {}};
struct B : A {int j; void f () {}};
int main () {
using namespace std;
cout << "ObjectArrays.c++" << endl;
{
// B a[] = {A(), A(), A()}; // error: conversion from "A" to non-scalar type "B" requested
}
{
A a[] = {B(), B(), B()}; // slice
a[1].f(); // A::f();
}
{
A* const a = new B[10]; // dangerous
a[0].f(); // A::f()
// a[1].f(); // undefined
// delete [] a; // undefined
static_cast<B*>(a)[1].f(); // B::f()
delete [] static_cast<B*>(a); // ~B::B() and ~A::A()
}
{
// vector<A>* const p = new vector<B>; // error: cannot convert 'std::vector<B, std::allocator<B> >*' to 'std::vector<A, std::allocator<A> >* const' in initialization
}
cout << "Done." << endl;
return 0;}
syntax highlighted by Code2HTML, v. 0.9.1