Airtamis
Airtamis

Reputation: 13

Troubles with reference variables/pointers an class members [C++]

I've been working on a project and have quite a few classes, a few of which look like this:

class A
{
    // stuff;
};

class B
{
    A& test;

public:
    B(A& _test) :
        test(_test)
    {};
    void doStuff();
};

class C
{
    A foo;
    B bar(foo);

    void exp()
    {
        bar.doStuff();
    }
};

This ends up breaking in class C when C::foo is not a type name. In my bigger project, where everything is broken up into their separate .cpp and .h files, I don't see that error if I #include"C.h" in B.h, but there is still an error in C.cpp where bar is completely unrecognized by my compiler (Visual Studio 2013). There error persists even if A& is an A* instead (changing the code from references to pointers where necessary, of course). Does anyone have any tips to what is going on here?

Upvotes: 1

Views: 35

Answers (1)

Barry
Barry

Reputation: 302718

This line of code:

B bar(foo);

Attempts to declare a member function named bar which returns a B and takes an argument of type foo. However, in your code, foo is not a type - it's a variable. I'm guessing you meant to initialize bar instead:

B bar{foo}; // non-static data member initializers must be done with {}S

or just write out the constructor:

C()
: bar(foo)
{ }

Additionally, this constructor assigns your reference test to the temporary _test:

B(A _test) :
    test(_test)
{ }

You want to take _test by reference:

B(A& _test) : test(_test) { }

Upvotes: 3

Related Questions