Search code examples
c++forward-declaration

C++ Bi-directional class association (Using forward declaration)


Quite new to C++ here, i'm trying to create a bi-directional One-To-Many association between two classes.

Here's what i achieved so far :

class_a.h

#ifndef CLASS_A_H
#define CLASS_A_H

class ClassB;
class ClassA {
public:
   std::vector<ClassB *> Bs;
};

#endif

class_b.h

#ifndef CLASS_B_H
#define CLASS_B_H

class ClassA;
class ClassB {
public:
   ClassA *classA;
   std::string name;
};

#endif

But, when testing the following code, output is showing me test.

Is b being deleted correctly ? Should not this code returns a 139 error ?

main.cpp

auto *a = new ClassA();
auto *b = new ClassB();

b->classA = a;
b->name = "test";

delete b;

std::cout << b->name << std::endl;

Thanks !


Solution

  • delete b;
    

    Once you delete b, it (and any other reference/pointer/iterator pointing to the same object) becomes invalid.

    The behaviour of indirecting through an invalid pointer to access a member is undefined.

    std::cout << b->name << std::endl;
    

    Here, you indirect through an invalid pointer to access a member. The behaviour of the program is undefined.

    Is b being deleted correctly ?

    I see no evidence to the contrary.

    Should not this code returns a 139 error ?

    I don't know what a 139 error is but no, C++ does not guarantee such error to be returned. Nothing is guaranteed when the behaviour is undefined.