1

I'm relatively new to c++ and so i don't know how to implement my problem. I will schematically present my problem instead of the actual code, hopefully this will give general solutions that other users can use as well.

I have:

  • a class A defined in a header A.h (with its proper A.cpp)

  • a class B in header B.h (with its proper B.cpp)

in this class B, I have a function that uses as argument an object of A (objA), does something with it, and returns this object.

How should I define that function so that the class B recognizes the "type" objA in its function? Is it done with pointers, templates,...?

Thanks! Roeland

Roeland
  • 13
  • 3

2 Answers2

0

Your headerB.h should #include "headerA.h". That would suffice.

Of course if you are going to change state of the object, you should pass it by pointer, something like void MyBMethod(objA* x);.

nullptr
  • 11,008
  • 1
  • 23
  • 18
  • And what if I have a third class, say C.cpp. It has to make the object of A (objA) and than it uses MyBMethod(objA x) Does it change anything? – Roeland Nov 03 '13 at 13:41
  • Then you need to #include declarations (header files) of both A and B into C.h (or into C.cpp if you prefer to use forward declarations in header files to minimize inclusions). – nullptr Nov 03 '13 at 19:33
0

There're there variants:

   // 1) by value
   // in B.h
   #include "A.h"
   class B {
   public:
     A foo(A a);
   };
   // in B.cpp
   A B::foo(A a) { /* a.do_something(); */ return a; }

   // 2) by reference
   // in B.h
   #include "A.h"
   class B {
   public:
     void foo(A& a); // can modify a
     void foo(const A& a); // cannot modify a
   };
   // in B.cpp
   void B::foo(A& a) { // a.change_something(); }
   void B::foo(const A& a) { // a.get_something(); }

   // 3) by pointer
   // in B.h
   #include "A.h"
   class B {
   public:
     void foo(A* a); // can modify a
     void foo(const A* a); // cannot modify a
   };
   // in B.cpp
   void B::foo(A* a) { // a->change_something(); }
   void B::foo(const A* a) { // a->get_something(); }
dnk
  • 661
  • 4
  • 5