user246392
user246392

Reputation: 3017

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.

Upvotes: 1

Views: 4116

Answers (4)

ALOToverflow
ALOToverflow

Reputation: 2699

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.

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361682

You cannot write like this:

 Object2 obj2(&obj1);

Use constructor to initialize objects, like this:

class Sample
{
private:
      Object1 obj1;
      Object2 obj2;
public:
     Sample(Object1 o1)  : obj1(o1), obj2(&o1)
     { 
     }
};

Read this to understand this in detail:

http://www.cprogramming.com/tutorial/initialization-lists-c++.html

Upvotes: 1

suszterpatt
suszterpatt

Reputation: 8273

You can't assign values to members like that in their declaration. You'll have to do that in the class' constructor.

MyClass
{
    private:
        Object1 obj1;
        Object2 obj2;

    public:
        MyClass()
        {
            obj2 = Object2(&obj1);
        }
};

Upvotes: 0

Victor Nicollet
Victor Nicollet

Reputation: 24577

In C++, you cannot initialize members as part of the class definition. This kind of operation should be done in the constructor:

myClass() : obj2( & (this->obj1) ) { ... }

This will usually generate a warning, but will be fine as long as obj2 does not use its constructor argument until the construction of myClass is complete.

Upvotes: 2

Related Questions