1
#include<iostream>

class A {

    public:
        void fun() { fun2(); }
        ~A() = default;
    protected:
        virtual void fun2() = 0 ;
};

class B : public A {
    protected:
        virtual void fun2() { std::cout<<"Hiiii";} 
};

class X {
    public:
        X(A& a) {
           a.fun();
        }  
};

class Y {

    public:
        Y( int x ) : val(x), x(B())
        {}
    private:
        int val;
        X x;
 };


 int main() {

    Y y(5);
 }

Am not able to figure out why am getting following compilation error:

prog.cpp: In constructor 'Y::Y(int)': prog.cpp:30:32: error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A' Y( int x ) : val(x), x(B()) ^ prog.cpp:21:7: note: initializing argument 1 of 'X::X(A&)' X(A& a) { ^

Chetan Kole
  • 137
  • 2
  • 7

1 Answers1

1

Because the constructor of X takes a reference, and you can't pass a temporary by reference.

To fix it, make X constructor take a const reference. And then, fun and fun2 should be made const for the code to compile.

Olivier Sohn
  • 1,292
  • 8
  • 18