c++ - Object B in object A and reference of object A in object B without pointers -
so wanted store:
- object b in object ,
- reference of object in object b
while not using pointers.
the difference between using pointers , references try avoid accessing syntax. don't want write '->' each time access object in object b.
code thought work throws segmentation fault:
a.h
#ifndef a_h #define a_h class b; class a{ b b; public: a(); }; #endif b.h
#ifndef b_h #define b_h class a; class b{ a& a; public: b(a &_a); }; #endif a.cpp
#include "a.h" #include "b.h" a::a():b(b(*this)){} b.cpp
#include "b.h" #include "a.h" b::b(b &_b):a(_b){} first thing thought causing segmentation fault using 'this' keyword (of uninititialized instance) in initializer-list, i've read long don't access should ok. constructors empty don't wrong.
is possible similar how doing it? , if no why , there allow me not write '->'?
edit: indeed there compilation errors because written pseudocode not paste unnecessary code here nobody has waste time. after writing pseudocode of course compiled.
goo.gl/dhlm6x
but runs without seg fault. guess there differently in project. have test time why doesn't work in project , post problem question have real answer.
at first might seem idea use references here , not mess pointers, don't this. why? reference meant link object can sure linked object lives longer reference.
so code
class b{ a& a; }; basically states: "for every object of type b there known, not changeable object of type a exists before object of type b created , still live @ time b-object destructed".
at same time code
class a{ b b; }; states: "every object of type a consists of object of type b", tells compiler allocate memory object of type a (including space b b), construct object of type b @ right position inside memory , construct object of type a. in example constructed after b , destroyed before b.
both statements exclude each other.
so either switch pointers (which state "the object knows object of type x" , can nullptr) or might consider doing this:
class combined{ a; b b; } and add functions need know both objects in combined class.
in standard found following problem , why shouldn't work @ all:
9.3.2 the pointer [class.this]
in body of non-static (9.3) member function, keyword prvalue expression value address of object function called. type of in member function of class x x*. if member function declared const(...)
so can say, this has defined behaviour "inside body of non-static member function". compilers allow this, typeid(this) or sizeof(this) in other parts of class, couldn't find in standard.
Comments
Post a Comment