#include <iostream>
#include <vector>

class A;
class B;

// a buffer contains array of A followed by B
// | A[N - 1]...A[0] | B |

class A
{
	size_t index;
	int a[4];
public:
    A(size_t index) : index(index) {}
    const B* getB() const { return reinterpret_cast<const B*>(this + index + 1); }
    void print() const { std::cout << "A[" << index << "]\n"; }
};

class B
{
	size_t a_count;
	int b[16];
public:
	virtual ~B() {}
	B(size_t a_count) : a_count(a_count) {}
	const A* getA(size_t i) const { return reinterpret_cast<const A*>(this) - i - 1; }
	void print() const
	{
		std::cout << "B has " << a_count << " As\n";
		for(auto i = 0; i < a_count; ++i)
		{
			getA(i)->print();
		}
	}
};

B* make_record(size_t a_count)
{
	char* buf = new char[a_count*sizeof(A) + sizeof(B)];
	for(auto i = 0; i < a_count; ++i)
	{
		new(buf) A(a_count - i - 1);
		buf += sizeof(A);
	}
	return new(buf) B(a_count);
}

int main() 
{
	std::vector<B*> vec;
	vec.push_back(make_record(2));
	vec.push_back(make_record(4));
	vec.push_back(make_record(8));
	
	for(auto b : vec)
		b->print();
}
