A practical guide to learning the basics of C++, programming concepts, functions, classes and object-oriented programming.
C++ is a general-purpose programming language that is widely used for software development, system programming, game development and competitive programming. It was developed by Bjarne Stroustrup as an extension of the C programming language.
One reason C++ is still important in Computer Science is that it gives programmers a high level of control over memory and system resources while also providing features such as classes, inheritance and polymorphism. Learning C++ also provides a strong foundation for understanding data structures and other programming languages.
In this guide, we will cover the basic syntax of C++, data types, operators, control statements, functions and the major concepts of object-oriented programming.
A simple C++ program can be used to understand the basic structure of the language. The following program displays a message on the screen.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
#include <iostream> includes the standard input
and output stream library.
main() is the function where execution of a C++
program begins.
cout is used to display output on the screen.
<< is the stream insertion operator used
with cout.
return 0; indicates that the program completed
successfully.
A token is one of the smallest meaningful elements of a C++ program. The compiler uses these elements to understand the structure of the code.
Common types of tokens include:
int, class, if and return.A data type tells the compiler what kind of value a variable is expected to store. Choosing an appropriate data type helps a program work with data correctly and efficiently.
| Data Type | Used For | Example |
|---|---|---|
| int | Whole numbers | int age = 25; |
| float | Decimal numbers | float price = 10.5f; |
| double | Decimal values requiring more precision | double pi = 3.14159; |
| char | A single character | char grade = 'A'; |
| bool | True or false values | bool passed = true; |
C++ also provides other types such as arrays, pointers, references, structures and classes for handling more complex data.
A variable is a named memory location used to store a value that may change during program execution.
int marks = 85;
cout << marks;
In this example, marks stores the value 85.
The value can be changed later in the program.
A constant is a value that should not be changed after it has been initialized.
const double PI = 3.14159;
Operators are symbols used to perform operations on values and variables. C++ provides several categories of operators.
Suppose a = 10 and b = 5.
| Operator | Expression | Result |
|---|---|---|
| + | a + b |
15 |
| - | a - b |
5 |
| * | a * b |
50 |
| / | a / b |
2 |
| % | a % b |
0 |
Control statements determine which parts of a program should execute and how many times a particular block of code should run.
The if statement is used when a program needs to make
a decision based on a condition.
int marks = 75;
if (marks >= 40) {
cout << "Pass";
}
else {
cout << "Fail";
}
If the condition marks >= 40 is true, the program
displays "Pass"; otherwise it displays "Fail".
A for loop is useful when the number of repetitions is
known or can be controlled using a counter.
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
The program prints the numbers from 1 to 5.
A while loop repeats a block of code as long as its
condition remains true.
int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}
A switch statement is useful when one value needs to
be compared with several possible cases.
int choice = 2;
switch (choice) {
case 1:
cout << "Add";
break;
case 2:
cout << "Edit";
break;
default:
cout << "Invalid choice";
}
A function is a block of code designed to perform a particular task. Functions make programs easier to organize because a task can be written once and called whenever it is needed.
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
cout << result;
return 0;
}
Here, the add() function receives two numbers and returns
their sum.
In call by value, a copy of the argument is passed to the function. Changing the parameter inside the function does not change the original variable.
void change(int x) {
x = 100;
}
int main() {
int a = 10;
change(a);
cout << a; // Output: 10
return 0;
}
In call by reference, the function receives a reference to the original variable. Changes made through the reference affect the original variable.
void change(int &x) {
x = 100;
}
int main() {
int a = 10;
change(a);
cout << a; // Output: 100
return 0;
}
C++ supports object-oriented programming, where programs can be organized around objects that contain data and functions.
The four commonly discussed principles of object-oriented programming are encapsulation, abstraction, inheritance and polymorphism.
Encapsulation means keeping related data and functions together and controlling how the data is accessed.
For example, in a bank account class, the account balance should not
normally be changed directly from outside the class. Methods such as
deposit() and withdraw() can control how
the balance is modified.
Abstraction means showing the important features of an object while hiding unnecessary implementation details.
For example, when you use a car, you can use the steering wheel and pedals without needing to know every internal detail of the engine.
Inheritance allows a new class to reuse and extend features of an existing class.
class Animal {
public:
void eat() {
cout << "Eating";
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking";
}
};
Here, Dog derives from Animal. The Dog class
can use the accessible members inherited from Animal in addition to
its own members.
Polymorphism means "many forms". In C++, the same function name or interface can produce different behaviour depending on how it is used. Common examples include function overloading and function overriding.
A class is a user-defined type that groups data and functions together. An object is an instance of a class.
class Student {
public:
string name;
int marks;
void display() {
cout << name << " " << marks;
}
};
int main() {
Student student;
student.name = "Rahul";
student.marks = 85;
student.display();
return 0;
}
In this example, Student is the class and
student is an object created from that class.
A constructor is a special member function that is automatically called when an object is created. It is commonly used to initialize the data members of a class.
class Rectangle {
private:
int length;
int width;
public:
Rectangle() : length(0), width(0) {
}
};
class Rectangle {
private:
int length;
int width;
public:
Rectangle(int l, int w)
: length(l), width(w) {
}
};
A copy constructor creates an object using another object of the same class.
class Rectangle {
private:
int length;
int width;
public:
Rectangle(int l, int w)
: length(l), width(w) {
}
Rectangle(const Rectangle &obj)
: length(obj.length),
width(obj.width) {
}
int area() {
return length * width;
}
};
Function overloading allows multiple functions to have the same name as long as their parameter lists are different.
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
The compiler determines which function should be called based on the arguments supplied.
Runtime polymorphism is commonly implemented using virtual functions. A base-class pointer or reference can refer to an object of a derived class, and the overridden function can be selected at runtime.
class Animal {
public:
virtual void sound() {
cout << "Animal sound";
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks";
}
};
int main() {
Animal* animal = new Dog();
animal->sound();
delete animal;
return 0;
}
Because sound() is virtual, the Dog implementation is
called even though the pointer type is Animal.
Templates support generic programming. They allow the same logic to be used with different data types instead of writing separate versions of a function for every type.
template <typename T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << maximum(10, 20);
return 0;
}
The function can work with different compatible types because
T acts as a placeholder for the actual type.
Exception handling provides a way to detect and handle exceptional
situations while a program is running. C++ commonly uses
try, throw and catch for this purpose.
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int numerator = 10;
int denominator = 0;
try {
if (denominator == 0) {
throw runtime_error("Division by zero");
}
cout << numerator / denominator;
}
catch (const runtime_error &e) {
cout << "Error: " << e.what();
}
return 0;
}
try contains code that may generate an exception.
throw reports an exceptional condition.
catch handles the exception.
C++ provides file stream classes for reading data from files and
writing data to files. The commonly used classes are
ofstream, ifstream and fstream.
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (!outFile) {
return 1;
}
outFile << "Hello from C++";
outFile.close();
return 0;
}
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream inFile("example.txt");
if (!inFile) {
cout << "Unable to open file.";
return 1;
}
string text;
getline(inFile, text);
cout << text;
inFile.close();
return 0;
}
Checking whether a file opened successfully is important because the file may not exist, may be inaccessible, or may be located at a different path.
Reading programming concepts is only the first step. Try solving small problems after studying each topic. This helps you check whether you can apply the concept instead of only remembering its definition.
C++ has a wide range of features, starting from basic variables and control statements and extending to object-oriented programming, templates, exception handling and file operations. It can look difficult when all of these topics are studied together, but learning them one concept at a time makes the language easier to understand.
If you are preparing for a Computer Science examination, first become comfortable with basic syntax, data types, operators, loops and functions. After that, spend more time on classes, constructors, inheritance and polymorphism. Finally, practice small programs rather than only reading definitions.
Regular practice is the best way to become comfortable with C++. Start with simple programs and gradually move to problems that combine multiple concepts.