0

Class are have written my classes in different files. Such as:

-main.cpp
-ClassA.cpp
-ClassB.cpp
-ClassC.cpp

main.cpp has the #include for all classes, but I also need to access Object instantiated from ClassA in main inside ClassB and ClassC.

main.cpp

#include "ClassA.cpp"
#include "ClassB.cpp"
#include "ClassC.cpp"

ClassA objA;
ClassB objB(objA);
ClassB objC(objA);

. .

classB.cpp

#include "ClassB.cpp" //How to avoid the double declaration and yet make the class recognizable?

class ClassB{
  public: 
   ClassA objA;
   ClassB(ClassA obj){
    this->objA = obj; // Is it the right way in C++?
   }
 };

I know it is not right. But why not? In Java makes sense.

  • Possible duplicate of [Resolve build errors due to circular dependency amongst classes](https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes) –  May 24 '19 at 04:12
  • 1
    You generally should not include `.cpp` files. There's a good explanation of the basic C++ file structure and build process here: https://stackoverflow.com/questions/333889/why-have-header-files-and-cpp-files#333964 – alter_igel May 24 '19 at 04:14
  • C++ is not Java. Things are done differently. – 1201ProgramAlarm May 24 '19 at 04:40
  • 1201ProgramAlarm. Thank you for the information. But I already knew it before I post this question (Hence I am posting the question). – Danilo Souza May 27 '19 at 05:11

1 Answers1

0

Declare your classes in header files. E.g. "ClassB.h":

#include "ClassA.h" // if it's referenced by the subsequent class declaration, you likely need that class's header file as well.

class ClassB{
  public: 
   ClassA objA;
   ClassB(ClassA obj);
 };

Implement your class in a .cpp file. E.g. "ClassB.cpp"

#include "ClassB.h"
ClassB::ClassB(ClassA obj)
{
    objA = obj;
}

Repeat for your other classes.

selbie
  • 100,020
  • 15
  • 103
  • 173