If in the form of code:

class clB; class clA { clB obj; }; typedef std::shared_ptr<clA> SHP_clA; class clB { SHP_clA pointerA; }; 

Will such a design work normally? What problems may occur with use?

Ps. I have definitions of these two classes in different * .h files (implementation of methods in separate * .cpp), how can I dock them correctly to each other? Now it gives an error in the clA class clA :

 error C2146: syntax error : missing ';' before identifier 'obj' error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 
  • Would you correct the code, eh? And then you have first class B , then some clB , then the mention of the identifier objB , which is not in the source ... give a minimal example (but accurate!) That reproduces the problem. While I see the main trouble is that you declare a type B field in A , but this B is an incomplete type. So you can only declare a link / pointer to B ... - Harry
  • By PS: There is no objB symbol in the objB so what kind of error can one guess. - tonal
  • @Dmitry, Harry has already written: ".. you declare type B field in A, but this B is an incomplete type. So you can only declare a reference / pointer to B" clB is an incomplete type where you are trying to declare the obj field in the clA class - tonal
  • @tonal understood, I will experiment. - Dmitry

2 answers 2

Problems are possible. For example, an attempt to delete an instance of clA when the destructor of instance clB , which will be called from the clA destructor. It is completely unclear why in this case to use std::shared_ptr

  • And if you use a regular pointer: clA * pointerA; ? - Dmitry
  • Then this problem will not be. - tonal

The main problem you have is

 class clB; // Неполное объявление (компилятор знает только // о существовании такого класса, но что внутри - не представляет) class clA { clB obj; // Вы пытаетесь создать **объект** класса, о котором // ничего неизвестно. В частности - сколько памяти для него выделить // (был бы указатель - понятно, все они одинаковы... а так?) }; typedef std::shared_ptr<clA> SHP_clA; class clB { SHP_clA pointerA; // Совершенно не возбраняется, тут можно даже сам // объект - к этому моменту компилятор знает все // о класса clA }; 

You'd better rewrite it like this:

 class clB; typedef std::shared_ptr<clB> SHP_clB; class clA { SHP_clB pointerB; //clB obj; }; 
  • Thanks, got it. - Dmitry