0
votes

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.

1
You generally should not include .cpp files. There's a good explanation of the basic C++ file structure and build process here: stackoverflow.com/questions/333889/… - alter igel
C++ is not Java. Things are done differently. - 1201ProgramAlarm
1201ProgramAlarm. Thank you for the information. But I already knew it before I post this question (Hence I am posting the question). - Danilo Souza

1 Answers

0
votes

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.