1. What is a C++ program?
A C++ program is a collection of objects that call each other's methods. Each object has state and behavior. A class is the template for these objects.
Full lesson: Cpp basic syntax
45 questions about C++ with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
A C++ program is a collection of objects that call each other's methods. Each object has state and behavior. A class is the template for these objects.
Full lesson: Cpp basic syntax
The main function is the entry point of every C++ program. The program starts execution at main. You can define other functions, but main is required.
int main() {
return 0;
}
Full lesson: Cpp functions
You declare a variable by writing its type and name. The type sets the size and range of the variable. The name must start with a letter or underscore.
int age = 25;
Full lesson: Cpp variable types
The unsigned modifier stops a variable from storing negative numbers. For integers, it doubles the positive range. You place it before the type.
unsigned int count = 4000000000;
Full lesson: Cpp modifier types
An if statement runs a code block when a condition is true. If the condition is false, the program skips the block. A non-zero value counts as true.
if (a < 20) {
cout << "a is small";
}
Full lesson: Cpp if
An if...else statement picks one of two code blocks. The if block runs when the condition is true. The else block runs when the condition is false.
if (a < 20) {
cout << "small";
} else {
cout << "large";
}
Full lesson: Cpp if else
A for loop repeats a block a set number of times. It has three parts: init, condition, and increment. The init part runs only once.
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
Full lesson: Cpp for loop
A while loop repeats a block while a condition is true. The program checks the condition before each pass. The loop stops when the condition becomes false.
int i = 0;
while (i < 5) {
cout << i << endl;
i++;
}
Full lesson: Cpp while loop
You declare an array with a type, a name, and a size. The size must be an integer constant greater than zero. Elements sit in contiguous memory.
int numbers[5] = {1, 2, 3, 4, 5};
Full lesson: Cpp arrays
A C-style string is a character array that ends with a null character. The null character marks the end of the string. The array size must include this extra character.
char site[7] = {'R','U','N','O','O','B','\0'};
Full lesson: Cpp strings
You define a class with the class keyword, a name, and a body. The body holds member variables and member functions. A class is a template for objects.
class Box {
public:
int width;
};
Full lesson: Cpp classes objects
A function definition gives the name, return type, parameters, and body. The body holds the statements that do the task. You call the function by its name.
int add(int a, int b) {
return a + b;
}
Full lesson: Cpp functions
A common mistake is a condition that never becomes false. The loop then runs forever. Check that the increment moves the variable toward the exit condition.
for (int i = 0; i < 5; i--) { // i moves away from 5
cout << i;
}
Full lesson: Cpp for loop
A common mistake is an index outside the array bounds. C++ does not check array bounds for you. An out-of-range index can corrupt memory.
int a[3] = {1,2,3};
cout << a[3]; // out of bounds
Full lesson: Cpp arrays
A common mistake is to forget the null character at the end. Without it, string functions read past the array. Always reserve one extra element for the null character.
char s[5] = {'H','e','l','l','o'}; // no null terminator
Full lesson: Cpp strings
C++ is a high-level object-oriented programming language. Bjarne Stroustrup began its design at Bell Labs in 1979. C++ expands the C language and runs on many platforms.
Full lesson: Cpp tutorial
C++ provides seven basic built-in data types. These types include integer, floating-point, double floating-point, character, wide character, and boolean types. The operating system allocates memory based on the data type.
Full lesson: Cpp data types
You place one if statement inside another if statement. The inner if runs only when the outer condition is true. This tests multiple conditions more precisely.
if (a > 0) {
if (b > 0) {
// both are positive
}
}
Full lesson: Cpp nested if
You place one loop inside another loop. C++ allows at least 256 nesting levels. The inner loop runs completely for each outer loop iteration.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
// runs 6 times total
}
}
Full lesson: Cpp nested loops
An abstract class has at least one pure virtual function. A pure virtual function uses '= 0' in its declaration. You cannot create objects from an abstract class.
class Box {
public:
virtual double getVolume() = 0;
};
Full lesson: Cpp interfaces
Inheritance lets you define a new class based on an existing class. The existing class is the base class. The new class is the derived class and reuses base class members.
class Dog : public Animal {
// Dog inherits from Animal
};
Full lesson: Cpp inheritance
The <string> header provides the std::string class. This class encapsulates C-style strings. It offers safer and easier string operations.
#include <string>
std::string name = "Alice";
Full lesson: Cpp libs string
The <list> container stores a collection of elements. It supports bidirectional iterators. You can insert and delete elements quickly at any position.
#include <list>
std::list<int> mylist;
mylist.push_back(10);
Full lesson: Cpp libs list
The <array> container provides a fixed-size array. The size is set at compile time. It offers better type safety than C arrays.
#include <array>
std::array<int, 5> arr = {1, 2, 3, 4, 5};
Full lesson: Cpp libs array
The STL is the Standard Template Library. It provides template classes and functions for common data structures and algorithms. The STL supports generic programming.
Full lesson: Cpp stl tutorial
Use the ofstream class from the <fstream> library. Create an ofstream object and open a file. Then write data with the stream insertion operator.
#include <fstream>
std::ofstream file("data.txt");
file << "Hello";
file.close();
Full lesson: Cpp files streams
A common mistake is a condition that never becomes false. This creates an infinite loop. Always update the loop variable inside the loop body.
int i = 0;
while (i < 5) {
// forgot i++
}
Full lesson: Cpp while loop
A common mistake is a missing brace. Without braces, the else binds to the nearest if. This changes the logic and causes wrong results.
if (a)
if (b)
x = 1;
else
x = 2; // else binds to inner if
Full lesson: Cpp nested if
A common mistake is forgetting the access specifier. The default access for a class is private. Use public inheritance when you want an is-a relationship.
class Dog : Animal { // private inheritance
};
Full lesson: Cpp inheritance
A common mistake is using a runtime size. The size of std::array must be a compile-time constant. You cannot change the size after creation.
int n = 5;
std::array<int, n> arr; // error: n is not constant
Full lesson: Cpp libs array
Use two slashes for a single-line comment. Use a slash and an asterisk to start a block comment. Close the block comment with an asterisk and a slash.
// This is a single-line comment
/* This is a
block comment */
Full lesson: Cpp basic syntax
A modifier changes the meaning of a base type. Common modifiers are signed, unsigned, long, and short. You place a modifier before the type name.
unsigned int count = 10;
long int total = 100000L;
Full lesson: Cpp modifier types
A declaration tells the compiler the name and type of a variable. A definition also reserves memory for the variable. You can declare a variable many times but define it only once.
extern int value; // declaration
int value = 5; // definition
Full lesson: Cpp variable types
Write the class name and then the object name. You can also pass arguments to a constructor. Use a dot to access the public members of the object.
class Box { public: int size; };
Box b;
b.size = 3;
Full lesson: Cpp classes objects
Include the <string> header and declare a std::string variable. The class manages memory for you. You can join strings with the plus operator.
#include <string>
std::string a = "Hello";
std::string b = a + " World";
Full lesson: Cpp libs string
Include the <fstream> header and create an ifstream object. Open the file and check that the open call succeeds. Use getline to read one line at a time.
#include <fstream>
#include <string>
std::ifstream in("data.txt");
std::string line;
std::getline(in, line);
Full lesson: Cpp files streams
Include the <typeinfo> header and use the typeid operator. The operator returns a reference to a type_info object. Call the name member to get a type name.
#include <typeinfo>
int x = 0;
const std::type_info& t = typeid(x);
Full lesson: Cpp libs typeinfo
Use the valarray class template from the <valarray> header. You can assign one value to all elements. You can also add two valarray objects element by element.
#include <valarray>
std::valarray<double> a(3);
a = 1.0;
std::valarray<double> b = a + a;
Full lesson: Cpp libs valarray
A common mistake is to forget the <string> header. Another mistake is to mix a C-style string and a std::string in one expression. Include the header and use std::string for both values.
#include <string>
std::string s = "text";
Full lesson: Cpp libs string
A common mistake is to use a file before you check that it opened. Another mistake is to forget to close the file. Always test the stream and close it when you finish.
std::ifstream in("data.txt");
if (!in) { return 1; }
// use the file
in.close();
Full lesson: Cpp files streams
A common mistake is to expect the same type name from every compiler. The name member can return different text on different systems. Do not compare the name string to a fixed value.
#include <typeinfo>
#include <iostream>
std::cout << typeid(1).name();
Full lesson: Cpp libs typeinfo
A common mistake is to use an index that is outside the array size. Another mistake is to forget that valarray has no bounds check. Check the size before you use an index.
#include <valarray>
std::valarray<int> v(3);
v[3] = 1; // wrong: index out of range
Full lesson: Cpp libs valarray
A common mistake is to use an iterator after the container changes. Another mistake is to forget the header for a container. Include the correct header and get a new iterator after a change.
#include <vector>
std::vector<int> v = {1, 2};
v.push_back(3);
Full lesson: Cpp stl tutorial
A common mistake is to forget the return statement in a function that returns a value. Another mistake is to return a type that does not match the declaration. Match the return value to the declared type.
int add(int a, int b) {
return a + b;
}
Full lesson: Cpp functions
A common mistake is to access a private member from outside the class. Another mistake is to forget the semicolon after the class body. Keep data private and add the semicolon.
class Box {
int size;
}; // do not forget the semicolon
Full lesson: Cpp classes objects