Search code examples
c++pointersheaderampersand

Object initialization problem in C++ header file


I am coding in C++, and I have private data members in the header file of a class.

private:
      Object1 obj1;
      Object2 obj2(&obj1);

So, the second object takes a pointer to the first object. When I try to compile the program, I get the following error:

"expected identifier before ‘&’ token"

Is there a way to instantiate the objects inside this class' constructor in the implementation file rather than its definition? How do I correct this error? The program won't compile.


Solution

  • What your compiler is telling you with this error is that you are trying to make a method called obj2, returning an Object2 that is taking a reference as a parameter. But it can't figure out what the type of the reference is.

    On the other hand if you want to set the reference before the construction of the object you can write something like this :

    Object2* obj2 = &obj1;
    

    Edit

    How do I correct this error? The program won't compile.

    Making your program compile is not always the best solution, maybe there is a reason why it won't compile and you have to understand why it is so. Simply correcting the error might not help your cause. As Nawaz pointed out in the comment, if the types Object1 and Object2 are different, it is possible that what you are trying to do is not the right thing.