Suppose, I want to make a class B with a pointer to another class A. In the constructor of A I want to construct B and passing it a pointer to this. In principle, this pointer can be a shared_ptr, correct? Then how do I make such a class with the assignment of the shared_ptr in the constructor?
I tried it in the code below. ClassB and ClassC are identical, with a pointer to ClassA which constructs instances of ClassB and ClassC. The only two differences are that ClassB holds a regular pointer and ClassC holds a shared_ptr to ClassA and that the code with ClassB is working and the code with ClassC is not. What am I doing wrong?
// Main.cpp : Defines the entry point for the console application. #include "ClassA.h" #include <iostream> int main(int argc, char* argv[]) { std::cout << "Create B and C separately, without a reference to A:" << std::endl; ClassB(nullptr); ClassC(nullptr); std::cout << "Create A, and through it B and C:" << std::endl; ClassA A; A.PrintHello(); A.getObjectB().getPointerToA()->PrintHello(); A.PrintHello(); A.getObjectC().getPointerToA()->PrintHello(); return 0; } // ClassA.h #pragma once #include "ClassB.h" #include "ClassC.h" class ClassA { private: ClassB objectB; ClassC objectC; public: ClassA(void); ClassB getObjectB() { return objectB; }; ClassC getObjectC() { return objectC; }; void PrintHello(); }; // ClassA.cpp #include "ClassA.h" #include <iostream> #include <memory> ClassA::ClassA(void) : objectB(ClassB( this )), objectC(ClassC( std::make_shared<ClassA>(*this) )) { std::cout << "Class A fully constructed" << std::endl; } void ClassA::PrintHello() { std::cout << "Hello" << std::endl; } // ClassB.h #pragma once #include <memory> class ClassA; class ClassB { private: ClassA* pointerToA; public: ClassB(ClassA* pA); ClassA* getPointerToA() { return pointerToA; }; }; // ClassB.cpp #include "ClassB.h" #include <iostream> ClassB::ClassB(ClassA* pA) : pointerToA(pA) { std::cout << "Class B constructed" << std::endl; } // ClassC.h #pragma once #include <memory> class ClassA; class ClassC { private: std::shared_ptr<ClassA> pointerToA; public: ClassC(std::shared_ptr<ClassA> pA); std::shared_ptr<ClassA> getPointerToA() { return pointerToA; }; }; // ClassC.cpp #include "ClassC.h" #include <iostream> ClassC::ClassC(std::shared_ptr<ClassA> pA) : pointerToA(pA) { std::cout << "Class C constructed" << std::endl; }