Department of Engineering

IT Services

Common Difficulties and Mistakes

Obscure Error Messages
- small errors in a simple-looking line can produce complicated messages like the following

Error 226: "", line 16 # No appropriate function found for call of
    'operator <<'. Last viable candidate was "ostream &ostream::operator
    <<(char)" ["/opt/aCC/include/iostream/iostream.h", line 509]. Argument of
    type 'class set<int,less<int>,allocator>' could not be converted to
     cout << "s1 = " << s1;

The ^^^^ symbols show which part of the line is at fault. In this case the compiler can't narrow down the problem, so next read the first (easiest) part of the error message. There's something wrong with the use of <<. Remember that in C++ many functions can be invoked by an operator - it all depends on the number and type of operands. In this case s1 (a set) isn't something that there's a matching function for - hence the error message. The compiler, trying to be helpful, gives the next best option - a function tied to << that can deal with a char.

Another example: the line double d = sqrt(4); produces the following error because the integer given to sqrt has to be promoted to a real, but the compiler doesn't know what kind of real.

Error 225: "", line 6 # Ambiguous overloaded function call; more than
    one acceptable function found. Two such functions that matched were "long
    double sqrt(long double)" ["/opt/aCC/include/cmath", line 107] and "float
    sqrt(float)" ["/opt/aCC/include/cmath", line 57].

Obscure declarations and definitions
- C++ has fewer keywords than many languages but it makes up for this by having many meaning attached to a symbol. For example '<' is used in #include lines, cout, in template definitions as well as meaning 'less-than'. This makes deciphering declarations hard. c++decl can sometimes help.

Deriving from Container Classes
- the container classes weren't designed to act as base classes: they don't have virtual functions. Use them as members of other classes instead.

Object creation
- The first 2 lines below create a string variable s. The 3rd doesn't create an empty string - it declares a function s that returns a string.
String s;
String s("initial");
String s();

Input and newline characters
- If you try to get a character then a string from the user with
cout << "Type a character: ";
cin >> ch;
cout << "Type a string: ";
you're likely to get an empty string because the >> operator leaves the typed newline in the input stream. One way round this is to use istream::ignore(INT_MAX, '\n');.