Two objects of same class reference each other.

Sep 7, 2018 at 4:07am
In the following example, obj1 and obj2 reference each other.
obj1 and obj2 are of the same class.
The compiler is giving me linker errors.

circular_dependency_other_obj.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "CClass.h"

CClass obj1(1);
CClass obj2(2);

int main()
{
    obj1.begin(&obj2); //these two objects reference each other
    obj2.begin(&obj1);

    obj1.print();
    obj1.printOther();

    obj2.print();
    obj2.printOther();
}

CClass.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef CLCASS_H
#define CLCASS_H

#include <iostream>

//class CClass; //forward declaration not needed

class CClass
{
    private:
	int id;
        CClass* ptrCClass;
    public:
	CClass(int id) : id(id) {}
        void begin(CClass* ptr);
        void printOther();
        void print();
};
#endif 

CClass.cpp:
1
2
3
4
5
#include "CClass.h"

void CClass::begin(CClass* ptr) { ptrCClass = ptr; }
void CClass::printOther() { ptrCClass->print(); }
void CClass::print() { std::cout << id << std::endl; }


Linker errors:
1
2
3
4
5
6
7
8
9
$ g++ circular_dependency_other_obj.cpp
/tmp/ccXO0s4R.o: In function `main':
circular_dependency_other_obj.cpp:(.text+0xf): undefined reference to `CClass::begin(CClass*)'
circular_dependency_other_obj.cpp:(.text+0x1e): undefined reference to `CClass::begin(CClass*)'
circular_dependency_other_obj.cpp:(.text+0x28): undefined reference to `CClass::print()'
circular_dependency_other_obj.cpp:(.text+0x32): undefined reference to `CClass::printOther()'
circular_dependency_other_obj.cpp:(.text+0x3c): undefined reference to `CClass::print()'
circular_dependency_other_obj.cpp:(.text+0x46): undefined reference to `CClass::printOther()'
collect2: error: ld returned 1 exit status 

What went wrong?
Last edited on Sep 7, 2018 at 4:33am
Sep 7, 2018 at 4:11am
You forgot to link the other .cpp.
g++ circular_dependency_other_obj.cpp CClass.cpp
Sep 7, 2018 at 4:34am
Thanks helios, that worked:
1
2
3
4
5
6
$ g++ circular_dependency_other_obj.cpp CClass.cpp 
$ ./a.out
1
2
2
1
Topic archived. No new replies allowed.