2

Here's my code

class B {
public:
    void bar() {std::cout<<"~";}
};

class A {
public:
    A() {b=B();};
    A(B arg_b): b(arg_b) {};
    void foo() {b.bar();};
private:
    B b;
};


int main() {
    A a;
    a.foo();  // works fine

    A aa(B());
    aa.foo();  // could not compile, but if I comment out this line only, it can compile.
}

I got this error message

error: request for member ‘foo’ in ‘aa’, which is of non-class type ‘A(B (*)())’ aa.foo();

I'm a beginner in c++, could some one please explain why this code could not compile? and what is the correct way to initialize a class member by passing in an instance?

M.M
  • 138,810
  • 21
  • 208
  • 365
dontloo
  • 10,067
  • 4
  • 29
  • 50
  • `A a(B()); a.foo();` should fail to compile. Please post real, complete code. [See here for posting guidelines](http://stackoverflow.com/help/mcve) – M.M Mar 02 '17 at 08:17
  • @M.M thanks for replying, I've edited the code (if you're suggesting that pass by reference cannot take rvalues) – dontloo Mar 02 '17 at 08:22
  • I'm not suggesting that. Read the posting guidelines link. – M.M Mar 02 '17 at 08:22
  • @M.M Hi, I've changed the question (since nobody's answered it yet), could you explain a bit (or throw me a link) why it won't compile? thanks! – dontloo Mar 02 '17 at 08:46
  • 1
    When you're facing compilation errors, it's considered polite to include those errors in the question. – molbdnilo Mar 02 '17 at 08:50
  • @molbdnilo thanks, I've added the error message – dontloo Mar 02 '17 at 08:51
  • `b=B();` is useless. Default constructor of B is already called in initialization list. – O'Neil Mar 02 '17 at 09:00
  • @M.M Hi, I have reproduced my initial question, and posted it here http://stackoverflow.com/q/42552832/3041068, would mind taking a look? thanks – dontloo Mar 02 '17 at 10:30

1 Answers1

4

A aa(B()); is a function declaration. So you cannot write aa.foo() because you cannot use . on a function.

The rule is (approximately) that if code could be parsed as either a function declaration or an object definition, then it is parsed as a function declaration.

Instead you could use A aa{ B() }; which cannot be a function declaration.

Also see this thread

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365