2

Here is a code snippet:

class test {

        public:
                test(){
                        cout<<"I am in default constructor ";
                }
                static void func(const  test &obj){
                        cout<<"I am in function ";
                }
        protected:
                test( const test &o){
                        cout<<"I am  in copy constructor ";
                }
};

int main()
{
        test::func(test());
}

The above code gives following error with g++ 3.4.6 (on Red Hat Linux) on compilation:

In function `int main()':

error: `test::test(const test&)' is protected

error: within this context

However if you compile with g++ 3.3.2 or g++ 4.4.3 or any other g++ version (on Red Hat Linux), it compiles successfully and gives following output:

I am in default constructor I am in function

In the above code, I have passed the temporary object (created by default constructor) to function func by reference. So why the compiler 3.4.6 is calling the copy constructor?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
jack_sparrow
  • 37
  • 1
  • 4
  • 1
    Duplicate of [why copy constructor is called when passing temp by const ref?](http://stackoverflow.com/questions/4733448/why-copy-constructor-is-called-when-passing-temp-by-const-ref) – Georg Fritzsche Feb 03 '11 at 09:33

1 Answers1

0

Most likely because older g++ versions (and I believe it stands for other compilers) were not fully c++ compliant and had more bugs then the current version. As you said, this works on a later version, therefore it is most likely fixed.

EDIT

by the way, have you tried changing compiler settings? Different optimization levels might have different bugs.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • 2
    http://stackoverflow.com/questions/4733448/why-copy-constructor-is-called-when-passing-temp-by-const-ref - It's not a bug. It's compliant. The behaviour was changed in GCC because it's a bit silly, and the language itself fixes it in C++0x. – Lightness Races in Orbit Feb 03 '11 at 09:37
  • @Tomalak Thanks for the reference. The behaviour is silly indeed, and I wasn't aware of 5.2.3 – BЈовић Feb 03 '11 at 09:42