c++ - How to access pointer of a class pointing to another pointer of a class pointing to a value -


i’m working on project has high multithreading between classes, need access value in class , want use pointers access described in following:

i have 3 classes: a.h

class a{ public: int myvalue; } 

in class a.cpp

class a{ a::a(){ myvalue=0; }  function(){ myvalue++;   } } 

now want access value in intermediate class called b because can access directly. in class b.h

class b{ public: *myptr1; } 

in class b.cpp

class b{   b::b(){   myptr1 = new a();   }    function (){   printf("my value = %d \n",myptrt1->myvalue);   } } 

when run program, output correct equal 5. however, need access value in third class use pointer second class access it.

let's called third class c, in class c.h

class c { public: b *myptr2; } 

in class c.cpp

class c{   c::c(){   myptr2 = new b();   }    function (){   printf("my value = %d \n",myptr2->myptrt1->myvalue);   } } 

when run program, output not correct. got values equal 0 , others negative values think second pointer pointing wrong memory location? question how access value correctly. try write code similar code simplicity because code big.

thanks in advance.

in simplified pseudocode have posted, accessing myvalue attribute correctly , since zero-initialized in a's constructor , being incremented afterwards, there no reason why value should become negative. seems rather caused bug (hidden within real code) rewrites myvalue's value.

but catches attention more have:

class c { public: c() { bptr = new b(); } b* bptr; 

now if lifetime of instance of b contained within instance of c tied lifetime of instance of c, seems reasonable bptr aggregated value ~> i.e. object automatic storage duration rather pointer:

class c { public: c() { } b b; 

which reduce ugly memory management connected working naked pointers these. code less error-prone.

or in case need instance of b shared between more objects, might consider setting constraint "instance of c can not exist without instance of b" (which cause class c not responsible existence of b):

class c { public: c(b& bref) : b(bref) { } b& b; 

Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -