I am trying to implement the composite "structural pattern". The attached code compiles but when I run the exe file the memory collapses.
Here is the code:
#include <iostream>
#include <iomanip>
class CTreeComponent {
public:
virtual void traverse(int)=0;
};
class CTreeLeaf:public CTreeComponent {
public:
CTreeLeaf(int wert):m_wert(wert){}
void traverse(int tiefe){std::cout<<m_wert<<" ";}
private:
int m_wert;
};
class CTreeComposite:public CTreeComponent {
public:
CTreeComposite():m_anzahl(0) {}
void add(CTreeComponent* elem){m_children[m_anzahl++]=elem;}
void traverse(int tiefe){
std::cout<<std::endl<<std::setw(tiefe*4)<<" "<<tiefe<<": ";
for (int i=0;i<m_anzahl;i++)
m_children[i]->traverse(tiefe+1);
}
private:
CTreeComponent* m_children[2];
int m_anzahl;
};
int main() {
int i;
CTreeComposite containers[99];
for (i=0;i<4;i++) {
containers[i].add(new CTreeLeaf(2*i));
containers[i].add(new CTreeLeaf(2*i+1));
}
containers[2].add(&(containers[3]));
containers[1].add(&(containers[2]));
containers[0].add(&(containers[1]));
containers[0].add(&(containers[2]));
containers[0].add(&(containers[3]));
for (i=3;i>=0;i--) {
std::cout<<"Container"<<i<<" "<<": ";
containers[i].traverse(1);
std::cout<<std::endl;
}
}
The error output:
(Unhandled exception at 0x004011df in Kompositum.exe: 0xC0000005: Access violation writing location 0x0063deb0.)
Does anybody has any idea why?
I am not so experienced, so it might be sth simple.
Does anybody know any better way to implement such a design pattern?
Thanks in advance.