Strange error! Compiler problem? Or code problem?!!!!!!!

  • Thread starter Pedro Miguel Carvalho
  • Start date
P

Pedro Miguel Carvalho

Greetings.

The following code does not compile and I can't see why! I'm using
C++Builder v6.0 (build 10.160).

<code>
#include <vector>

class test
{
bool Fixed( unsigned int I ) const;
bool& Fixed( unsigned int I );

private:

std::vector<bool> pFixed;

};

bool test::Fixed( unsigned int I ) const
{
return pFixed;
}

bool& test::Fixed( unsigned int I )
{
return pFixed; // error: [C++ Error] test.cpp(21): E2357 Reference
initialized with 'bool', needs lvalue of type 'bool'
}
</code>

If the bool's are replace with int,float,double,a struct, a class, a enum it
compiles and works correctly.
The following code <code> pFixed = true; </code> also works so
"pFixed" is a lvalue.

Is seems to be a compiler error but how can this error go unnoticed?

Thanks,
Pedro Carvalho
 
C

Catalin Pitis

The problem is in the code.

vector< bool> has a different implementation than the generic vector<T>
class.
The operator[] returns a vector<bool>::reference type, which for vector<
bool> is an inner class having defined a conversion operator bool() which
returns a boolean value, not a boolean reference.

In conclusion, the operator[] has as return type different than bool&, which
can be (and is) automatically casted to bool (and not bool&).

However, in the posted example the Fixed methods can be removed. Use direct
access to pFixed member.

Catalin
 
P

Pedro Miguel Carvalho

Ignore it!
I'm having a strange day, no special cases allowed :).

Pedro Carvalho

| Greetings.
|
| The following code does not compile and I can't see why! I'm using
| C++Builder v6.0 (build 10.160).
|
| <code>
| #include <vector>
|
| class test
| {
| bool Fixed( unsigned int I ) const;
| bool& Fixed( unsigned int I );
|
| private:
|
| std::vector<bool> pFixed;
|
| };
|
| bool test::Fixed( unsigned int I ) const
| {
| return pFixed;
| }
|
| bool& test::Fixed( unsigned int I )
| {
| return pFixed; // error: [C++ Error] test.cpp(21): E2357 Reference
| initialized with 'bool', needs lvalue of type 'bool'
| }
| </code>
|
| If the bool's are replace with int,float,double,a struct, a class, a enum
it
| compiles and works correctly.
| The following code <code> pFixed = true; </code> also works so
| "pFixed" is a lvalue.
|
| Is seems to be a compiler error but how can this error go unnoticed?
|
| Thanks,
| Pedro Carvalho
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top