mr_azad mr_azad - 3 days ago 6
C++ Question

Conceptual confusion

This might me a silly problem. But I am not getting the conceptual problem in the program.

I want to pass the pointer of class Child in a global function and access that pointer object from different parts of the project just by including Child.h

Problem: the following problem does not work when I do get_Child()->number_1 in the main.

Solution: if I include the Child.cpp in the main, and inline the Constructor or
if I declare the constructor in the Child.h instead of Child.cpp

Query request. What is the reason for this behavior? A way how I can declare the Constructor in Child.cpp and does not have to include Child.cpp in the main.cpp

main.cpp

#include <iostream>
#include "Child.h"
//#include "Child.cpp"

using namespace std;

int main(){

Child *pC = new Child();
cout << "direct = " << pC->number_1 << endl;

cout << "with function = " << get_Child()->number_1 << endl;

}


Child.h

#ifndef CHILD_H_
#define CHILD_H_


class Child;
static Child * pointer_Child;

inline void save_Child(Child * p_C){
pointer_Child = p_C;
}

inline Child * get_Child(){
return pointer_Child;
}


class Child {
public:

Child();

//Child(){
// this ->set_Child();
//}

void set_Child(){
save_Child(this);
}

int number_1 = 10;
};

#endif /* CHILD_H_ */


Child.cpp

#include "Child.h"

//inline Child::Child(){
// this ->set_Child();
//}

Child::Child(){
this->set_Child();
}

Answer

Do not declare static variables in a header (outside of classes) like this:

static Child * pointer_Child;

It will create a variable in every compilation unit that includes the header. And they are not accessible from outside the translation unit.

Instead, make pointer_Child extern and provide an implementation in the CPP as follows:

Header:

extern Child* pointer_Child;

CPP:

Child* pointer_Child;

And never include a CPP file.

Comments