Here, i am trying to create a Nth level hierarchy but doesnt let me point to outer-class of an inner class and getting an access violation error. But the latter version workes.
What is my mistake? Is this about the scope of newly created inner-loops? But they are created inside the class so it shouldnt be problem should it?
// atom.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
class a
{
public:
int x;
a * inner;
a * outer;
a(int n) //creates an inner a
{
n--;
x=n;
if(n>0){inner=new a(n);}else{inner=NULL;}
inner->outer=this;//Unhandled exception at 0x004115ce in atom.exe: 0xC0000005:
//Access violation writing location 0x00000008.
}
};
int main()
{
a * c=new a(5);
a * d=c;
while((d->inner)) //would print 4321 if worked
{
std::cout<<d->x;
d=d->inner;
}
getchar();
delete c;
d=NULL;
c=NULL;
return 0;
}
But this works:
// atom.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
class a
{
public:
int x;
a * inner;
a * outer;
a(int n) //creates an inner a
{
n--;
x=n;
if(n>0){inner=new a(n);inner->outer=this;}else{inner=NULL;}
//works without error
}
};
int main()
{
a * c=new a(5);
a * d=c;
while((d->inner)) //prints 4321
{
std::cout<<d->x;
d=d->inner;
}
getchar();
delete c;
d=NULL;
c=NULL;
return 0;
}
Do you think all they are auto-deletet when i just delete c ?
When you do this:
the condition
n>0will eventually not hold (at the 5th call), soinnerwill beNULL, and then you runt into undefined behavior (and the crash) when you attempt to dereference it (inner->outer).