Chapter 1

Writing a Simple C++ Program

Every program has one or more functions, one of which must me main.

int main() {
    return 0;
}

A function has four elements:

  1. Return type
  2. Function name
  3. Optional list of parameters
  4. Function body

Input and Output Library

  • istream and ostream are two types defined in the iostream library.
  • Stream is a sequence of characters read from ir written to an IO device.
  • Library defines four objects - cin (istream), cout (ostream), cerr(ostream) and clog(ostream). Each of this object is associated to the window running the program.

std::cout << "This is a string literal" << std::endl;

  • This is a statement which executes an expression.
  • Expression yields a result and is made up of one or more operands and an operator.
  • string literal is a sequence of characters enclosed in double quotes.
  • endl is a manipulator. Writing endl results in writing a new line and flushing the buffer associated with the device.
  • A condition is an expression that yields wither true or false.
  • A block is sequence of zero or more statements enclosed by curly braces.

while(std::cin >> val) sum += val;

How is the condition evaluated?

  • >> operator returns its left operand, which is istream object cin here.
  • The while loop condition is evaluating the cin object.
  • Testing an istream object is akin to testing the state of the stream.
  • An istream becomes invalid when it hits EOF or encounters an invalid input.
  • An istream in an invalid state causes the condition to yield false.

Classes

Classes are used define data structures. A class defines a type along with a collection of operations that are related to that type.

Primary design focus of C++ is to make it possible to use define class types which behave like the built-in types.

Member function is a function defined as part of a class.

  • Also known as methods.
  • Usually a member function is called on behalf of an object.
  • Use dot operator to call a method of an object.
  • Dot operator only applies to an objects of a class type. Left operand must be an object of class type and right operand must name a member of that type. Result of the dot operator is the member named by the right operand.
  • Usually dot operator is used to call the member function.
Last modified May 28, 2025: Fix weights of cpp primer (7877b0b)