c++ - Why access from child class to the field of other exemplar of superclass crashed this field? -
c++ - Why access from child class to the field of other exemplar of superclass crashed this field? -
inside sec extender class, when called method clone(s) value of field changing.
listing:
#include<iostream> using namespace std; class set { public: set(int min,int max) { num_bits=max-min+1; num_bytes=(num_bits+7)/8; elems=new int8_t[num_bytes]; for(int i=0; i<num_bytes; i++)elems[i]=0; minelem=min; maxelem=max; }; void add(int n) { int bit=n-minelem; elems[bit/8]|=(1<<(bit%8)); }; void del(int n) { int bit=n-minelem; elems[bit/8]&=~(1<<(bit%8)); }; bool has(int n) { int bit=n-minelem; return(elems[bit/8]&(1<<(bit%8))); } void print()//str { int i=0; { cout<<(has(i+minelem)?"1":"0"); i++; if(i%8==0)cout<<" "; } while(i<num_bits); } ~set() { delete[] elems; }; public://rotected int num_bits,num_bytes,minelem,maxelem; int8_t *elems; }; class exset:public set{ public: exset(int min,int max):set(min,max){} exset(set s):set(s.minelem,s.maxelem){/*clone(s);*/} void clone(set s){ //for(int i=0;i<num_bytes;i++){int x=s.elems[i];cout<<elems[i]<<'='<<s.elems[i]<<'/';} }; }; main() { char *p="abczabxyz"; set s('a','z'); s.add(*p); while(*++p!='\0'); s.del('b'); s.print(); cout<<endl; for(char c='a'; c<='z'; c++)if(s.has(c))cout<<c; cout<<endl; //delete &s; exset es(s); for(char c='a'; c<='z'; c++)if(s.has(c))cout<<c; };
expected:
10100000 00000000 00000000 01000000 11000000 00000000 00000001 11 aczabxyz aczabxyz
get:
10100000 00000000 00000000 01000000 11000000 00000000 00000001 11 aczabxyz fginqrvwghqrvw
the next line source of memory problems.
exset(set s):set(s.minelem,s.maxelem){/*clone(s);*/}
when execute
exset es(s);
a temporary re-create of s
made in phone call constructor of exset
. when temporary destructed, deletes memory held elems
.
when s
destructed, same memory 1 time again deleted. leads undefined behavior. in case, produces wrong results. in other cases, programme might crash.
you can resolve particular problem using
exset(set const& s):set(s.minelem,s.maxelem){/*clone(s);*/}
however, proper fix, provide re-create constructor , re-create assignment operator in set
. understand why, rule of three.
c++ class inheritance superclass
Comments
Post a Comment