2

please have a look at this program and the error it is generating:

#include <iostream>
using namespace std;
    class A
    {
    public:

        virtual void f(){}
        int i;
    };

    class B : public A
    {
    public:
        B(int i_){i = i_;} //needed
        B(){}              //needed
        void f(){}
    };

    int main()
    {

        //these two lines are fixed(needed)
        B b;
        A & a = b;

        //Assignment 1 works
        B b1(2);
        b = b1;

        //But Assignment 2  doesn't works
        B b2();
        b = b2; // <-- error
    }

upon compilation, I get the following error:

$ g++ inher2.cpp 
inher2.cpp: In function ‘int main()’:
inher2.cpp:32:10: error: invalid user-defined conversion from ‘B()’ to ‘const B&’ [-fpermissive]
inher2.cpp:14:6: note: candidate is: B::B(int) <near match>
inher2.cpp:14:6: note:   no known conversion for argument 1 from ‘B()’ to ‘int’
inher2.cpp:32:10: error: invalid conversion from ‘B (*)()’ to ‘int’ [-fpermissive]
inher2.cpp:14:6: error:   initializing argument 1 of ‘B::B(int)’ [-fpermissive]

Can you help me find the problem? thank you

rahman
  • 4,820
  • 16
  • 52
  • 86

2 Answers2

6

Your "B b2();" is the 'vexing parse' problem of C++ (see here - the 'most vexing parse' takes the ambiguous syntax further).

It looks to the C++ compiler that you are declaring a function (a pre-declaration).

Check it out:

int foo(); //A function named 'foo' that takes zero parameters and returns an int.

B b2(); //A function named 'b2' that takes zero parameters and returns a 'B'.

When you later do:

b = b2;

It looks like you are trying to assign a function (b2) to a variable (b). To call a constructor with zero parameters, call it without the parentheses and you'll be fine:

B b2;

For more information, see:

Community
  • 1
  • 1
Jamin Grey
  • 10,151
  • 6
  • 39
  • 52
  • 2
    That is not "most" vexing parse. It is just vexing parse! – Nawaz Mar 14 '13 at 06:18
  • @Nawaz what do you mean :) the title of his link to wikipedia says it is "Most" vexing! – rahman Mar 14 '13 at 06:25
  • 2
    Most vexing is the format "***B b2(B())***". Vexing is the format "***B b2();***". The Wikipedia article shows an explanation of the former. – Jamin Grey Mar 14 '13 at 06:28
2
B b2();

It is a function declaration, not a variable declaration!

The function name is b2 which takes no argument, and returns object of type B.

Search for vexing parse in C++.

Nawaz
  • 353,942
  • 115
  • 666
  • 851