[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [Samples] / c++.FAQ
[Index] [Contents] [Source Text] [About] [Notation] [Copyright] [Comment/Contact] [Search ]
Fri Mar 21 07:41:01 PDT 2008

Contents


    FAQs on C++

      Why are you teaching Linux?

      Total cost of ownership, reliable networked systems, + hard core professionals use it.

      Why are you teaching C++?

      Used in many industries. After C++ other languages are easy! It is also leads to programs that execute quickly.

      It is like a tool box full of very sharp power tools. You need to know what you are doing but you get a lot of power and speed in return. C++ is very much the parent of most modern (web-based) languages.

      How is C++ used in Games?

      You need a good graphics and user interface library plus a "games engine" that understands the physics of objects. C++ acts as the glue connecting these components. The components are probably also written in C and/or C++.

      How do you develop a program?

      Very carefully!

      First: understand the problem. Second: work out how the user will use the program. Third: sort out the data needed. Fourth: design objects to store the data and do useful things. Fifth: write code for the objects, user, data, ....

      Why are you teaching UML?

      The only industrial diagramming language for software.

      How has computer programming changed through out the years?

      Here is my quick and personal list.
      1. 1800s Ada Lovelace programs Babbage's Analytical Engine.
        <1940s Programs were written for human computers to execute in English and mathematics.
      2. 1940s Programs written by changing the machine hardware (in secret).
      3. 1950s Instructions written as numbers and stored in memory.
      4. 1960s First programming languages mimic mathematical formula(FORTRAN, ALGOL) or managerial English(COBOL). Programs became complicated so we split them up into independent pieces called modules. Flowcharts used to design programs. Many local low level languages. Mainframes.
      5. 1970s Structured programming. Programs are designed using Pseudocode and diagrams and split into functions. Pascal. C. Unix. Minicomputers.
      6. 1980s Data Abstraction. We started to group functions around data and let other parts of the program only see those functions. Ada. The IBM PC.
      7. 1990s Objects. C++. Java. The Web.
      8. 2000s Modeling: diagrams of objects etc used to analyze problems and design solutions. Perl, Ruby, C#, Python

        How does a computer work

      9. Here is a model of a computer: A person sitting at a desk with a simple calculator. They read instructions in a book called the "program". They write down answers on a work pad(RAM) and also use them in future calculations. They have an in tray (input) were they get data, and an out tray where they put data (output).

        What is the function of the backslash character

        The backslash (\) character is use in C++ and many other languages to change the meaning of the following character in a string. The backslash and the following characters/number form an escape sequence. or to indicate an strange character that is illegal or untypable. Here is a short list of escape sequences.
        • \n Newline
        • \t Tab
        • \" Double quotation marks(")
        • \\ A real backslash
        • \007 Beep

        Can you explain more clearly how translate human-readable code to machine code.

        Not really -- it is rather complex. Take CSCI320 and CS570. Meanwhile
        1. Recognize the basic words and symbols in the code.
        2. Use the syntax to parse the symbols into a structure and reject syntax errors.
        3. Scan the stored structure and generate some machine code.
        4. Optimize the code (a dark art).
        5. Output the result.

        What translates mnemonic instructions into machine code?

        The assembler.

        Why is C++ faster

        It is compiled and so the code doesn't have to be parsed many times. It also lets the programmer get close to the machine.

        What are namespaces

        I C++ the names that programmers create are all placed in a namespace. This lets different programmers use the same name for different purposes, even in the same program. For example, most of the standard libraries place their names in "namespace std". SO the official name for the C++ Output stream is
         		std::cout
        but the
         		using namespace std;
      10. statement makes it OK to omit the "std::".

        Are there any standards for C++

        Yes the is one international and American national standard C++. Any variations you meet are non-standard.

        Explain how a bug gets past the compiler

        A compile only checks to see if you've followed the grammar, the syntax of C++. It doesn't check to see if you've written down rubbish.

        Computability theory shows that it is impossible for a computer to diagnose all bugs that can happen.

        To quote a friend: "Nothing is foolproof, fools are too ingenious".

        Is HTML in use and is it like C++

        HTML is still in use. It is totally unlike C++ in its purpose, syntax, and meaning.

        What aren't all compilers the same

        (1) Economics (2) human error.

        Floating point notation

        Floating point is John Von Neumann's invention. It lets computers do arithmetic with "real numbers" easily. The basic circuits do calculations with whole numbers: integers. It takes special hardware or software to handle numbers that are not whole numbers.

        You know if you want to calculate "1.23 * 32.1" that you can calculate "123*321" and then place the decimal point in the answer. This is the idea behind floating point. We express numbers as a mantissa and an exponent. The exponent tells us where to put the point: 1.23 = 123E-2 and 32.1 = 321E-1, for example. The "E" indicates the "Exponent" and is short for using "10 to the power". Now if you do the math you will see that you multiply the mantissas and add the exponents to get the answer:

      11. 123E-2 * 321E-1 = 39483E-3 = 39.483

        In other words the point is allowed to float inside the number...

        Modern computers provide a form of floating point that uses Binary notation rather than decimal. It is easy to use (just forget it!), give approximate but good answers, and is slower than integer arithmetic.

        Most computers provide two different sizes of floating point number: normal and double length. Double length numbers take up twice the space and are slower.... but the give a more accurate answer.

        Choosing data types: int vs double vs string

        Use double for all measurements. Use int only for counting things. Only use 'float' for a measurement if you have a small (20th century) computer.

        Beware of dividing ints!

         		2 / 3
        is 0. If you don't want to do integer division -- you need doubles.

        For any kind of character handling (like -- "insert a comma") you need strings not ints or doubles.

        Why do we include iostream

         		#include <iostream>
        is needed for programs that do IO (Input and Output). It tells the computer how to connect C++ to the user's keyboard (cin) and display(cout).

        What are cin and cout

        Normally cin is the users input to the computer and cout is the place for out to the user.

        Can you create a program to prompt and read variables as it runs

        Yes:
         		#include <iostream>
         		using namespace std;
         		int main()
         		{
         			cout << "Prompt";
         			type variable;
         			cin >> variable;
         			...
         		}

        Explain range restrictions on numbers

        Most computer hardware gives a fixed amount of storage to each type of number (int has 16 bits, float 32 bits perhaps). Going outside the range (overflow) can produce bad results.

        You can get more storage for int by asking for long int in the program. You can also ask for long double rather than double.

        The old float data type is OK for fast calculations with larger errors.

        Can we do a number theoretic modulus in C++

        Yes.
         		n % m
        is the modulus of n mod m.

        Why do uninitialized numeric variables have random numbers

        The initial value is what ever has been left behind in the allocated memory by the previous program. This is unpredictable. The program will often work sometimes and produce incorrect answers else where.

        Initialize doubles and ints will loose points!

        Do I like shortcutting assignment and arithmetic

        Only in private. Avoid it in this class!

        What kind of comment do I like the // or the /*...*/

        I like both. Any comment is worth more than none. I'll equal credit for both. Please use both and discover the good and bad features.

        Is the underscore _ used as a space holder in identifiers

        Yes!

        What does a compiler turn C++ into

        A lot of numbers. By way of "assembler code".

        Are we going to get a list of C++ commands

        There are at least 100 basic types and you don't need them all. It is best to add them one at a time to your notes and "cheat sheet".

        If you really need to get a description of the options try [ ../samples/c++.syntax.html#Statements ]

        What are C Strings

        Before C++ existed with easy to use "strings" there was an older language (C) with primitive and dangerous "char-star" ( char* ) string. Briefly: each was an array of characters terminated by a null character.... and we will talk about arrays later in this class.

        What are strings for

        Strings are a common form of data: a number of characters in a row. You should use them for data that is not numeric: no addition or subtraction.

        Examples: names ("Horstmann"), SIDs("123-45-6789"), pieces of text ("The quick brown fox jumps over the lazy dog."), an so on.

        Why do we need a third string when we concatenate two words

        The expression
         		"Fred" + "Flintstone"
        produces
         		"FredFlintstone"
        with no space, unlike
         		"Fred" + " " + "Flintstone"
        that produces
         		"Fred Flintstone"

        What and why substrings

        Substrings are parts of strings.... We need them to slice and dice nonnumerical data. Typically people gives character data and we need to search it and extract the pieces that we want out of it.

        Example: given

         		int main()
        as input to a compiler we will need to extract and recognize the "main" in the line.

        When to use getline and >> with strings

        Use >> to read in words separated by spaces. For example given
         		123 ++ grandma
        then
         		cin >> a >> b >> c;
        would put "123" in a, "++" in b, and "grandma" in c. But
         		getline(cin, s)
        puts the whole line "123 ++ grandma" into s.

        So, use getline when you want to parse the user's input yourself.

        Can C++ do other Math functions than the elementary ones in cmath

        I can't find any ones in the standard C++ library [ lib-numerics.html ] except the ones that Horstmann lists on page 59.

        I did a search on the web and found Matpack [ matpack_frame.html ] (free), and there is also MatLab and the NAG(Numeric Algorithms Group) library.

        For other functions you can use a reliable reference like [AbramowitzStegun6465] (in the CSUSB library and my office).

        My program rejects every string function and operation

        Insert
         		#include<string>
        at the start of your program.

        What happens if you don't give enough room in formatted output

        You probably get some asterisks or a wrong answer.... why not try it in a simple program?

        How is input and output used in a program

        Input occurs when the user types some data and it's value is placed in a variable inside a program. Typically done early in a program to get ready to compute other values that are output to the user.

        What is int cents = value % 100;

        The "%" operate calculates remainders (moduli). If value is an integer that holds a large number of cents -- say 12345 cents, then it is 123 dollars and 45 cents. If you divide by 100
         		12345/100
        you will get the number of dollars and if you computer the remainder
         		12345 % 100
        you get 45 -- the number of cents.

        Can C++ do equations or algebra or calculus

        No.

        There are expensive software tools that can help solve equations, do algebra, and do much of the calculus. Example: Mathematica. These may have been programmed in C++.

        Can computers do infinity

        No -- well not very well and usually only by accident.

        However -- the standard floating notation developed by IEEE and adopted on most computers has a value that prints as "inf" for the result of calculations that should have produced infinite answers.

        When to use '

        Only when there is a single character in the quotes: '(' and you don't need to do any string operations on it.

        We will return to characters later.

        Explain the dot notation

        Some functions are only defined if they are applied to an object. They are called methods. They are used like this:
         		object . function_name ( arguments )
        Examples include "length" and "substr" that operate on strings.
         		myName . length ( )
         		myName . substr (start, length )

        We will meet many more example next week...

        Why isn't Microsoft C++ the same as the standard

        MONEY.

        What is the most efficient way to program the tic-tac-toe display

        Horstmann's "comb" technique is rather neat. I would define and use
         		const string comb="+--+---+--+\n|  |  |  |\n";
        for example.

        What is the most efficient way to program a tic-tac-toe program

        The hard parts are (1) teaching the computer what the rules are, and (2) teaching it how to win. A simple idea: list every possible position and tabulate the best move for it.... but this needs a "vector" to hold a large number of positions and moves. We'll do vectors later in this class.

        You have to do a lot of analysis and design to do this project well.

        What is the difference between a class and an object

        A class is a collection of many similar objects. In mathematical terms, a class is a set of objects. Thus "Fido" is an object and "Dog" is "Fido"'class.

        When we say that foo "is a" foobar we imply that foo is the object and foobar is its class.

        Does it matter: YES. Bugs and wasted time is the lot of those who confuse sets with elements.

        In a program an object is a little bit of memory reserved for a special purpose. The class has little memory of its own and defines what the purpose of its objects are: Time, Employee, Point, ...

        Can I construct one object inside another

        Yes.... but the class has to define how it works.

        Explain #define

        This is a compiler directive. Suppose you have
         		#define answer 42
        in a program then the compiler remembers that "answer" means "42" and deleted the line.... but when ever it sees a line with "answer" it replaces it by "42". So,
         		cout << answer+1<<endl;
        is replaced by
         		cout <<42+1<<endl;
        before the the rest of the compilation takes over.

        What are boundary test cases

        A boundary test case is some input data that produces output that will change a lot if we made a small change in the input data. It is a test to see if a program can handle such changes.

        What is a WAN

        WAN is an acronym for any largish network. A small network is a LAN. The largest network is a network of connected networks called the Internet.

        Can you ++ a double

        You can ++ a int or a double variable, but not a constant: [ ../cs201/doubleplusplus.cpp ]

        What is return 0;

        A return statement computes a value and terminates a function leaving the value behind.

        C++ programs execute the main function until they hit their return statement. That is when they stop. And they leave the zero as a signal to the operating system that zero errors occurred.

        Can C++ calculate derivatives and antiderivative.

        Not easily. You would have to teach C++ how to store and manipulate formulas and then all the rules of the calculus. It is easy in Maple and Mathematica to differentiate functions. In languages like Prolog and LISP it is not to difficult to code the rules of differentiation.

        Oddly antiderivatives are difficult for human (intelligent) mathematicians. I don't think there is an algorithm and with no algorithm you can't write a program.

        How does a member function differ from a nonmember function


        1. member functions are a part of a class, other functions are not.
        2. member functions must be applied to an object like this
           		object.function(data)
           		lengthOfStr = str.length();
        3. other functions mustn't be applied to object.
           		diagonal=sqrt(x*x+y*y);

        Is animation possible in C++

        Yes... but you need (1) a better graphic library like "Open GL" and knowledge of the calculus (up to multidimensional) and physics.

        What is the difference between = and ==

        This statement
         		variable = expression ;
        changes the value of the variable so that it is the current value of the expression.

        This expression

         		expression1 == expression2
        is a test to see if the two expressions have the same value at this time. It is often used in ifs and whiles.

        Explain the selection operator

        This is the only operator in C++ that has three arguments. It is also the only use of a question mark ('?') in C++.

        The expression

         		test ? expression1 : expression2
        is a neat way to for a program to select on of two expressions to evaluate. However you probably won't need it in CSci201.

        A common purpose is to express mathematical function that are do different things in different ranges. For example a function that was 0 when x is less than or equal to 0 and 1 otherwise (the Heaviside function) is written

         		(x<=0 ? 0 : 1)
        These functions tend turn up in applied mathematics and physics rather than pure math. For example when I was working on the stresses in a large steel reaction vessel for a chemical company I modeled it as a cylinder with a spherical cap. The (?:) operator let me describe this simply.

        Explain input validation

        The data that comes into a computer (input) is often in the wrong format, missing, or illogical. Input validation makes sure that such bad data is rejected rather than being mis-processed.

        It is possible to write programs that ask the user to correct invalid data. They tend to be complicated. It takes time to plan them correctly and some advanced programming to handle them well. An example is: what happens if you forget your password.

        Explain if vs if/else

        The if allows a program to choose between doing nothing or doing something:
         		if(sender == "dick@csci.csusb.edu")
         		   return 1;

        The if/else lets the program choose between two different sets of operations -- an either-this-or-that choice:

         		if(sender.is_local() )
         		   message.goesTo("silicon.csci.csusb.edu");
         		else
         		   message.goesTo("mailer.csusb.edu");

        To choose the right one for a program, you have to work out, in detail, how you plan to solve the problem. Use pseudo-code or a diagram to do this. Then you can see where you have an optional behavior(if) and where you need a choice of two actions (if/else).

        Why line up braces and indent statements

        (1) You will not forget any.

        (2) You won't get lost in your code.

        (3) You will look good to other programmers (and bosses).

        When can I leave out the braces in an if or if/else

        Precisely when the program has a choice of executing exactly ONE(1) statement in one of the branches.

        The braces turn a sequence of statements into a single statement. if and else control ONE (1) statement only.

        The following do precisely the same thing:

         		if(x<0)
         		   cout <<"x is negative\n";
        VS
         		if(x<0)
         		{
         		   cout <<"x is negative\n";
         		}
        The first is shorter and easier to type. The second is easier to change if we need to add a statement inside the if.

        What is the difference between return 0; and return 1; in a main function

        The first sends a 0 to the operating system. UNIX treats this as a signal of success: Zero errors.

        The other sends a 1 and UNIX treats this as a signal of something having failed.

        When should I #include the string library.

        First it does no harm (the program gets a bit bigger when compiled).

        Second, it is not needed if you don't do any of the operations defined in it: substr, length, concatenation.

        Third, if you include it now, you won't have to in the future when the program gets more complex.

        Fourth: Many people start coding by copying a file that has3 or 4 #includes and that "using namespace..." and "int main()"... and their name in a comment just so they can get to the meat of the problem quicker.

        Can I put an if/else inside an if/else? Should I use braces

        Yes you can (and will). I use braces when ever it gets complicated.

        What are loops for

        Loops tell the computer to repeat the same computation many times. They are used to process repetitive data in files, produce interesting patterns in graphics, carry out iterative algorithms, and wait until something happens.... and much more.

        How do you avoid infinite loops

        First, never write a loop that looks like this
         		while ( ____ == ______ )
        since the values of the two expressions can jump all over the place and never become equal.

        Second, by being careful. In other words you choose a terminating condition that you can guarantee will become true some time. For example if the loop starts while(x<10) then x should increase each time the body of the loop is executed. If it is while(x>=17) then x should get smaller in each cycle.

        A sound discipline (but not easy) is to calculate how often each loop will repeat its body as a function of the arguments. This leads to the discipline of the analysis of algorithms that is in the core of computer science.

        Now some loops do not follow these two guidelines and yet they still always stop after a finite number of steps. These are subtle loops and need careful design, testing, and checking. You need to use loop invariants.

        What are loop invariants

        A loop invariant is any boolean expression or fact that remains true as the loop runs. It should start true, and it won't change, so it ends up still being true, however many times we repeat the loop.

        For example in the following loop

      12. s = Σ [ i=1..n ] ( i*i ) is always true:
         	s=0; n=0;
          while (n<100){
         		s=s+n*n;  n=n+1;
         	}
        So at the end when n==100:
      13. s = Σ [ i=1..100 ] ( i*i )

        This is a complex topic that needs some high powered logic to really understand. I cover them in CSci556 (senior level formal methods).

        If I have an infinite loop how can I terminate the program

        In Windows call up the task manager, find the process and click "End Task" with your fingers crossed.

        In Unix, hold down the Control key and tap the letter C key. In rare cases an expert can use the Unix kill command to terminate a program.

        If a program is running on a workstation with nobody there, for a long time.... push the on/off button on the CPU. Reboots are emergency operations but sometimes it is the only way to stop a maliciously breeding program.

        What is a sentinel value

        A sentinel value is a special input value that is found after the real data has been read or processed. It signals that the data is complete.

        How do you test for input failure or end of file

         		cin.fail()
        is a good test. You can also test
         		cin >> blah
        as it is executed and inputs data:
         		while(cin>>number)
         			cout << sqrt(number) << endl;

        What is a Boolean variable

        A Boolean variable is declared to have type bool:
         		bool variable;
         		bool variable=true;
         		bool variable=false;
        To some extent, bool behaves as if it was declared like this:
         		typedef enum {false, true} bool;
        with three special operations: and, or, not.

        So a Boolean variable is a named piece of memory that is used to remember the truth or falsity of something. A Boolean variable only needs a single bit of data (one Binary digIT). Floats, ints, and doubles need a lot more space. Doubles are always approximations.

        Use one any time your program needs to remember if something is true later in the computation.

        Boolean Joke -- Do you have tea or coffee for breakfast?

        Yes.

        Booleans and loop-and-a-half

        In a loop-and-a-half problem we have to repeat a sequence until some event happens inside the loop. The test is outside the loop -- we need to know if the event happened somewhere else. Booleans are about remembering events for the future.

        Here is the loop-and-a-half pattern.

         		bool event_happened = false;
         		...
         		while( not event_happened )
         		{
         			...
         				event_happened = (test for event here);
         			...
         		}

        Can you give an example of a function with multiple parameters

        Here is a function that calculates the length of the hypotenuse of a right triangle given the base and height: [ ../cs201/09multi.cpp ]

        What is the relationship between a function and a parameter?

        There are several relationships.

        First, a function is declared with formal parameters. These are (normally) local variables. They get their initial value when the function is called.

        Second, when a function is called it is given some expressions as actual parameters. These are (normally) evaluated and the values are given to the function.

        Note: the exception is parameters "passed by reference" which we will discuss later.

        Notice that each actual parameter must match the corresponding formal parameter. If it doesn't one of two things happen:

        • The compiler gives you an error message.
        • The compiler inserts casts to force the actual values to fit the formal parameters.

        What is a predicate and how do we use it.

        A predicate is any function that returns a Boolean value.

        You use it to test the truth and falsity of properties you are interested in as the program runs.

        You use predicates in conditions mainly: if(....) and while(....). For example

         		if( near(x,y) ) ...
         		while ( odd(n) ) ...
        Notice the nested parentheses. One pair for if/while and one for the call.

        In some groups of programmers there is a tradition of adding a 'p' to predicates... and indeed this conventions tends to include conversation like:

         		Lunchp.
        to ask questions.

        What is a side effect?

        A side effect occurs when a function changes something out side the function. For example:
         		int glob=0; //evil global variable
         		....
         		int f()
         		{
         		   glob=glob+1;  //sneaky change to global variable
         		}
        Here calling
         		f();
        changes glob.

        Note: invisible side-effects on global variable are not a good idea.

        Why are side-effects a bad idea

        Experience!

        Plus: there are better ways of getting what you usually need -- classes.

        How do functions help you write big programs?

        First: when you plan what functions to use, you develop an organization for the code. You divide it into a number of separate sub-problems. And as in ancient times, "divide and conquer" is a good strategy.

        Secondly, you write the functions once and call them several times. This makes the program smaller, any way.

        When should you put a function before the main function?

        Nearly always.

        One exception is when you declare the function header before the main program

         		void fun(int argument);
        (notice the semicolon!) and define it later
         		void fun(int argument){ .....}
        (NO semicolon, but has braces...)

        The other exception is when the function is in a separate file and you "#include" it in the program, but here again you must do this before calling the function.

        Why should you put a function before calling it?

        The compiler doesn't know what to make of the call unless it has been told the name of the function and how many arguments it has.

        Why do we put comments before functions?

        To help people understand what the function does. They read the comments and skip the complications.

        It doesn't take long before we forget what a function is supposed to do, so the person we help, is often ourself.

        When we have a return in a function do we still need one in main?

        Yes. Each function should have its own return value and so needs at least one "return" statement.... including "main".

        Exception: procedures with nothing returned (void).... don't need a return.

        How do we modify the values of parameters inside functions?

        You can do this but it has no effect on the actual argument unless you use "pass by reference".

        What is the easiest way to say "A or B" in a condition?

         		(A) or (B)

        Will we use any other #includes

        Perhaps....

        Can we put an #include later in a program

        Included files are designed to work if they come first in a program because they define functions.

        Bad things can sometimes happen if you do it later in the code.

        Can I use C++ to create programs that I can sell?

        Ask Bill Gates and Paul thingie..... Microsoft makes lots of money selling C++ programs.

        But get a lawyer before getting into serious business. You can get badly hurt.

        Explain more about the condition in a while statement.

        The condition is tested and the loop body is entered if the result is true. The condition can be as complicated as you like.

        Which is the compile command "g++... " or "./...."

        The compile command starts "g++" because it calls the compiler called "g++". The "g" is for "Gnu" and "++" from "C++".

        Is a class a holder for a bunch of functions?

        Yes. It is not a function but a collection of functions.

        A class also lists the data to be found in all its objects. So it is also a holder for a bunch of variables.

        A class also has a number of objects (initially none) because it defines how to construct new objects.

        How do you modify or change the value of a private data field?

        A private data field can not be changed from outside the class. You have to call a member function of the class that changes it. These functions are called mutator functions.

        What is the purpose for declaring an accessor function with const?

        This tells the compiler to make sure that you don't accidentally create a mutator that changes the data in the class. The const is short for constant, and the data fields are forced to be constant when the function is called.

        When an accessor is called the data fields in the object are retained. And the const enforces this!

        Do you have to define functions before classes?

        NO. You can declare non member functions like main anywhere. You can only define a member function after they are declared in the class.

        So typically classes come first and then functions.

        How does encapsulation work?

        The compiler won't let you do anything to an object that is not declared to be public in its class. This puts a "capsule" around the contents of the object.

        What is an interface?

        An interface is a list of functions that you can use -- public member functions.

        An example: Watch interface
        FunctionReturnsEffect
        get_time()Timeno change
        start()nonestarts the stop watch
        stop()nonestops the watch
        get_timer()intreturns number of seconds since starting the stop watch...
        set_time(t:Time)nonethe watches time is set to t

        What is the difference between implicit parameters?

        When you call a member function you apply it to an object and can also pass some data to it:
         		object . function ( data );
         		summer . add ( data );
        The data is called the explicit parameter(s). The object is called the implicit parameter.

        When we define a function, we don't mention the implicit parameter. The word implicit means we don't mention it.

        For example the function below adds numbers to the total of a particular object but doesn't say which:

         	Summer::add(int data)
         	{
         		total = total + date;
         	}
        The total is always the total that is in the object mentioned in the call:
         		object.add(20);

        How does a class differ from a function?

        A class contains functions.... But is not a function.

        You can call a function. You can not call a class.

        A class constructs objects. Most functions do things to existing objects.

        A function can return a value. Classes have no value to return. They define a new type of value that you can use.

        When are global variables used in C++?

        When you don't know any better!

        When a group of functions share some data then you need a class to hold both the data and the functions.

        Explain getline and >>

        Use getline to get a complete line of data from the user... ending when the tap the "Enter" key.

        Use ">>" only when you know what type of data comes next. Use getline when you can't predict the type of the input data. the getline function returns a string and you can then explore the string and figure out what is in it.

        What do two colons do?

        The two colons are used in C++ to relate a name to the class or namespace in which it is a member. A function like
                 void C::F(...)...
        is member of a class named C. It's own name is F. It is rather like they way we (mostly) have a family name and a personal name -- call me
                 Botting::Richard.

        What are the differences between && || and or?

        In C++ "&&" is the same as "and". They are both operators used in writing conditions: A and B (A && B) is true precisely when both A and B have the value true. It is false otherwise. Similarly, "||" means the same thing as "or" and these are also used in writing conditions. However A or B (A || B) is true if either A or B has the value true. It is false only when both A and B are false.

        What do default constructors do for you?

        When a class has a default constructor it means you can create new objects with out worrying about any parameters -- the default constructor will define a suitable object for you. You don't have to have a default constructor and it can be anywhere in a class description. How ever they are useful whenever you know what a typical object looks like.

        How do special constructors differ from the default constructor?

        They have parameters. C++ matches each declaration and construction by using the type of the parameters. It searches all of them looking for the right number and right types.

        Can you have a class with no constructors?

        You can write a class without any constructors, but the C++ compiler will then add a default constructor that does nothing:
                 MyClass::MyClass(){}
        To stop strangers from constructing objects you make all the constructors private. This is an advanced technique and needs more experience and knowledge than we have time for in CSci201.

        What are mutators for?

        The are used to change the data values in an object. They are chosen to reflect real life changes in the real world. Mutators change the internal state of the object.

        Why can't I use a constructor to mutate an object?

        Making a new object is different to changing an existing one. So I guess that the C++ designers decided that someone this confused should be stopped...

        How do you indicate whether the implicit parameter is passed by reference or value?

        It is always passed by reference! There is no choice here.

        Why do some of the book's classes have two constructors and others only one?

        Why not?

        You should have the right number of constructors for the job the class has to do. No more and no less.

        How do I get the right number of constructors.

        With some experience you will be able to get this right by thinking about the different ways that an object might need to be created.

        If in doubt do the absolute minimum for the program in hand and add new ones when needed.

        Are overloaded functions important?

        Overloaded functions (member and non-member) are important. You can not avoid using them. And you will need to create new ones as well. The C++ compiler matches function calls with function definitions. It does this by looking at the name (easy) and also by looking for a function that needs the data you have given it.

        Do you have to use I in a loop?

        No. You can use any variable name you like as a counting variable. The traditional names are: i,j,k,l,m,n.

        Can there be more than one constructor in a class?

        Yes. They must have different types and numbers of parameters. They are overloaded.

        Is programming an art or a science?

        Yes. We can teach the science part.... but the art is something you will have to develop for yourself.

        Must an accessor be a member function?

        Yes. The purpose of an accessor is to access private data. Only functions that are members of a class can do this.

        What is a CASE tool?

      14. CASE::="Computer Added Software Engineering", by analogy with "CAD" Computer Aided Design, a tool that helps you develop higher quality software typically by putting a graphic front end on the way to code.

        What is the difference between implicit and explicit parameter?

        Explicit parameters are written in parentheses after the function name. The implicit parameter appears before the "dot" in a function call but is not mentioned inside the function definition -- it is implicit. Operations on the data members are done to the parts of the object that appears before the dot in the calls:
         		implicit . function_name( explicit );
        and hidden in the body of the function:
         		private:
         		Type data;
         		...
         		public:
         		Type function_name( formal_explicit_parameter)
         		{ // a ref to `data` turns into `implicit.data` from the call
         		}

        Can you define an object variable that is not initialized by a constructor?

        This is simple (and dumb) (1) forget to define a default constructor in the class.

        (2) declare the object variable with no parameters:

         	class_name object_variable;

        Hey presto! You've got an object full of garbage data. And:

      15. GIGO::="Garbage in, Garbage Out".

        Why are member function important to classes?

        Object are used via their class's member functions. No functions, no use. So you get a useless class.

        Functions provide limited and controlled access to data. UML class box relate to the code?">

        How does the layout of the UML class box relate to the code?

        It doesn't. The UML puts the data first, in C++ you can put it last. Similarly the UML has the functions at the bottom, in C++ they can be anywhere.

        The UML uses position to signal the difference between operations and attributes. C++ uses special syntax. UML diagram when should you do them?">

        There is a lot of info needed for an UML diagram when should you do them?

        Start simple and add information as needed.

        Don't put all the details at first. Grow the diagrams and compartments: name, then add some data, then add some functions, ....

        First use UML as a rough sketch, then work out the detail and code them. Then do a nice tidy UML diagram to summarize what you've done when you present your work to others.

        What is the purpose of the ampersand in a function header?

        It means that the parameter in the call MUST be a variable. It also means that what ever is done to the formal parameter inside the function, actually is done to the variable that was the actual parameter.

        Why does revealing less information give more flexibility to improve a class?

        When information about the inside of a class is not revealed, then people can't rely on what you did when they use your class. So you can safely change what you wrote without breaking their code.

        Why do we have both member and non-member functions?

        C++ inherits "naked" functions from C, and it is too late to change that.

        Also sometimes you have need for a simple function and do not need the hassle of putting a class around it and declaring objects to get access to ONE LITTLE FUNCTION....(sorry to shout... I feel better now).

        What is overloading a function?

        A function is overloaded when the same name has different types of arguments. The compiler will pick the definition that fits the data types in the call of the function.

        Do most programming jobs require understanding the UML?

        It will help..... and a lot of job adverts mention it.

        Can you have a function called 1 or 2?

        No.

        Are there any programming languages that can be used to process themselves?

        Yes. C++ is one of them. Our 'g++'/'c++' compiler is written in C++.

        Will there be any use for computer programmers now that programs can write programs?

        Yes.... there is a definite future because computer programs are essentially rather stupid compared to a human being. It takes a human to figure out what the problems are and then to choose what needs to be programmed. A computer also has some definite limits (covered in the Upper Division Theory courses), and a smart human is needed to avoid the need to program these.

        Several times in the last 40 years somebody has produced a new language claimed that:
        LanguageClaim
        LISPWe can now program an artificial intelligence.
        COBOLManagers can now write programs in English.
        TLOThis is The Last One you'll need.
        PrologYou can describe the problem in logic and Prolog finds the solutions.
        In every case, the claim turned out to be false.

        When do we use p and q in C++?

        These variables can be used for Boolean variables. The p stands for proposition and the q is the next letter in the alphabet.

        However it is better to use a name that means something, like

         		end_of_file
         		bad
         		too_big

        Mostly they are used in teaching and learning Booleans, logic, and programming.

        Is a dangling else attached to the wrong if?

        Yes.

        How do you get complex logic right

        A couple of rules: (1) THINK, and (2) THINK.

        It helps to walk through complex cascades of if-else-if-else. It helps if you draw diagrams of complex logic. Flowcharts and "digraphs" can be a great help... especially combined with some logic.

        And it helps even more to show your thinking to other people you work with.

        Finally thorough testing is GOOD.

        Can you explain the difference between && and ||?

        It helps to practice with lots of Boolean expressions.

        But the fact is that most natural languages are not very good at distinguishing these to ideas. They did take more than 1800 years for them to appear in logic, mathematics, and philosophy.

        In real projects it is almost always a good idea to tabulate all the conditions and what needs to be done with them. Computer Scientists have developed many techniques, notations, and tools for this purpose and we cover them in several parts of the curriculum.

        What are the Boolean Operations used for?

        Expressing complex conditions.

        A complex Boolean expression can simplify a complex set of if-else statements. For example, for all conditions, P and Q, and statements A

         	if(P)
         	    if(Q)
         	      A
        (with no elses) is simpler as
         	if( (P) and (Q) )
         	      A
        (and often the ()s can be left out).

        Explain symmetric and asymmetric bounds in a loop

        A loop typically starts by allocating a value to a variable. In other words, the variables starts out equal to a value.

        The end of a loop can be specified in two common ways:

         		while( variable < bad_values )
        or
         		while( variable <= last value)

        In the second case we end up with the variable equal to the bound. This is like it starting out equal to a lower bound. Horstmann therefore calls it: symmetric.

        For each loop ask: does it go on until a bad value must be stopped, or until the last good value.

        Again: THINK!

        Explain switch statements

        The switch statement can be used to simplify some complex pieces of logic. It is only helpful when you need to make a choice between more than two different cases, AND the choice is made by looking at an int, bool, of char (character).

        It doesn't work when the choice depends on doubles or strings.

        Other than that they are very simple:

         	switch(Expression)
         	{
         	   case Value:
         	      DoSomething;
         	   break;
         ...
         	}
        The Expression is evaluated and its Value found in the set of cases. The case selects a sequence of statements that ends with a break; statement. At the break; the computer jumps to the end of the switch and exits it.

        What is the difference between nested ifs and a sequence of if else if else?

        An if-statement divides the code into two pieces:
         		if(Condition)
         		{
         		   TruePart
         		}
         		else
         		{
         		   FalsePart
         		}
        Either part can have another if-statement inside it. When an if appears in the TruePart we say that it is a nested if.

        Nested ifs tend to be for complex and type conditions.

        We can also have an if inside the FalsePart. Often, the FalsePart is a single if-else

         		if(Condition)
         		{
         		   TruePart
         		}
         		else
         		{
         		   if(anotherCondition)
         		   {
         		      FalseTruePart
         		   }
         		   else
         		   {
         		      FalseFalsePart
         		   }
         		}
        Then we simplify the syntax to
         		if(Condition)
         		{
         		   TruePart
         		}
         		else if(anotherCondition)
         		{
         		   FalseTruePart
         		}
         		else
         		{
         		   FalseFalsePart
         		}

        This a common structure that appears when we have a series of either-or operations.

        How Can you define a variable that is not initialized in a constructor?

        By forgetting to put the code in the constructor.

        Can you initialize a data field when you declare it in a class and outside a constructor?

        No.

        How does if-else and switch differ?

        if-else is a 2-way choice but a switch can have any number of alternatives.

        The if-else tends to be less buggy.

        Why is lazy evaluation lazy and what does it mean?

        Lazy evaluation means that the program does not evaluate every part of an expression unless it has to. In particular we know that false and p is false for any value of p and so there is no point in testing p. Similarly with true or p.

        Lazy evaluation lets the program run quicker.

        It also allows an unsafe part of a condition to be ignored unless we know it is OK:

         		D>=0 and sqrt(D) < 3.0

        Explain pass by reference with classes

        A member function is defined and called with pass by value or pass by reference just like any other function.

        However, the implicit parameter is actually passed by reference.

        Why does Dr. Botting Hate the Do Loop?

        Because he has had lots of bugs when he has used it.

        How does the for loop differ from the while loop?

        A while statement has one part: the condition tested at the start of the loop plus the body:
         		while ( condition ) body

        A for statement has three parts: the initialization, the condition, and the increment, plus a body that is repeated.

         		for(initialization; condition; increment ) body.

        The for loop does the work of a more complex while:

         		{ initialization;
         		  while( condition )
         		  {
         		     body
         		     increment
         		  }
         		}
        Since many loops do have the three parts of a for statement, it is worth using it rather than the more complex while.

        What is the difference between a "for" loop and a "do" loop?

        First a do loop always executes its body before testing its condition. A for loop tests the condition before it executes the body.

        A do loop has a condition and a body. A for loop has initialization, condition, increment, and body.

        Inside the body of any of the looping constructs while, do-while or for what does a break and continue command do?

        The break command jumps you out of the loop entirely.

        The continue command jumps you to the bottom of the loop and then lets it repeat (via testing the condition).

        Is there a limit to nested loops?

        No.

        Could you explain more about the nested loops?

        Sometimes we have a problem that contains the same problem many times inside it. This demands a loop. If the inner problem also contains another loop, you'll need a nested loop to handle it.

        One of the commonest forms is reading and writing tables.

         	A table has many rows.
         	A row has many items.

        So the code looks like

         	Process Table
         	loop
         		Process Row in the Table
         		loop
         			Process Item in Row
         		end loop
         	end loop

        An example: write a program to output a simple multiplication table. It has 12 rows numbered 1 to 12 and 12 columns numbered 1 to 12. The item in row r and column c has value r * c. Like this

           1   2   3   4   5   6   7   8   9  10  11  12
           2   4   6   8  10  12  14  16  18  20  22  24
           3   6   9  12  15  18  21  24  27  30  33  36
           4   8  12  16  20  24  28  32  36  40  44  48
           5  10  15  20  25  30  35  40  45  50  55  60
           6  12  18  24  30  36  42  48  54  60  66  72
           7  14  21  28  35  42  49  56  63  70  77  84
           8  16  24  32  40  48  56  64  72  80  88  96
           9  18  27  36  45  54  63  72  81  90  99 108
          10  20  30  40  50  60  70  80  90 100 110 120
          11  22  33  44  55  66  77  88  99 110 121 132
          12  24  36  48  60  72  84  96 108 120 132 144
        Here is the code [ ../cs201/mtable.cpp ]

        Now figure out what this [ ../cs201/mtable2.cpp ] program does.

        Can you explain the char ch; more clearly?

         		char ch;
        This creates a one byte piece of storage called "ch". You can store a single character in it. Single characters are not strings. They are found inside strings. A single character constant or literal is written
         			'?'
         			'a'
         			'\n'

        In C and C++ chars are also numbers in the range 0..255. As a result you can do arithmetic on them. For example:

         			'a' + 2
        is
         			'c'

        In consequence, we can go through the whole alphabet like this

         		for(char ch='a'; ch <='z'; ch++) ...

        What is De Morgan's Law?

        This is a law of logic published in the 1800's by Augustus De Morgan. It states that for all logical values p and q:
      16. not( p and q) == ( (not p) or (not q) )
      17. not( p or q) == ( (not p) and (not q) )

        You can prove this using truth tables. Try it!

        Is there any reason to seed the number generator more than once? If not, why make a function for it? Why not just add it to the beginning of main()?

        I completely agree.

        What are the commonest errors that happen in classes with member functions

        First there are all the errors with normal functions -- forgetting to specify the returned type, forgetting an '&' on a reference parameter, ... and so on.

        You have to be sure that functions have the right names and that the prototype/header matches its definition.

        With member functions you can access member data... and so these give rise to extra errors using up the wrong variable.

        What is an oracle

        An oracle is a program that is given test data (possibly random) and predicts the correct result. You can then run the real program and find out if it produces the same results. Notice that an oracle is often good enough for deployment as the real solution to the problem...

        In UNIX your test shell script might look like this

         		generate >test.data
         		oracle <test.data >correct.out
         		program <test.data >test.out
         		diff correct.out test.out
        Which lists the lines where the oracle has done something different to the program.

        How does a test harness work

        A test harness is just a normal main program the exercises the class/functions by calling them. It may out put results or use the assert function to test them.

        You have lots of code like this:

         		TestClass object;
         		assert(object.value() == correctvalue);
         		object.doSomething(data);
         		assert(object.value() == correctvalue2);

        When should I use arrays and when vectors?

        Use arrays only when you know the maximum number of items that can be in the array before you compile the program. Arrays have a fixed number of items. Vectors can grow and contract as items are pushed and popped.

        Use arrays when their size is pre-specified and you need the program to run very quickly or do a lot of calculation. Vectors are slower than arrays because they are dynamic.

        In the future you will meet an advanced technique that lets you delay fixing the size of an array until after the program has started. However, once the storage is allocated to this "dynamic array" it can not expand or contract. If more data is needed then you must get more storage, copy the data to it and change the address of the array. But now you have merely duplicated the effort of the people who programmed the "<vector>" library.

        In what kind of application would you use arrays

        When speed is important and the maximum amount of data known in advance. classic areas include

        Device drivers -- Low level functions driving hardware in an operating system.

        Numerical methods solving large mathematical problems.

        Embedded systems -- running inside military weapons and domestic appliances.

        What is an array index

        It is a number or int expression placed between "[" and "]" after the name of an array:
         		array_name [ index ]

        What are the bounds of an array

        These are the two fixed values that define the largest and smallest index that can be safely used. The low bound is always 0 in C/C++/Java. The upper bound, in C/C++, is determined when you declare the array. The upper bound is the index of the last element is one less than the size of the array.

        Declare array

         		type name [ size ];
        then the bounds are
      18. 0 .. size - 1

        What is a bound error

        This is a programmer's mistake of going outside the bounds. This is not detected by the compiler. Typically they suddenly make a program behave very badly -- segmentation faults, frozen computers, stupid output.... quite unexpectedly. They are the commonest way that hackers can break into systems.

      C++ Background

        What makes a computer translate its 0s and 1s into a language we can understand

        Programs. Luckily most of the input and output is translated by code that is in a special <iostream> library so we don't have to worry to much about how this happens in this course... it is all "High Energy Magic".

        How does a Control unit talk to other devices

        It use the computers "bus" -- a set of "wires" that connects all the parts of the CPU. Each "wire" can transmit a single bit {0,1} of information. The power of the CPU depends on how wide this "highway" is. We have had chips with 4 bit, 8 bit, 16bit, 32 bit, and 64 bit buses.

        What were the first computers used for

        Pretty much what computers are used for now: mathematical calculations and data processing. This was all in "batch mode". You provided the input and got the answers days or even weeks later.

        Then came real time and interactive applicati