Built as an extension of C, C++ is one of the most used and powerful programming languages that supports classes. Hence, features such as object-oriented programming can be easily adopted by C++ which helps in creating complex programs. It allows developers to create highly efficient software. It has been extensively used to develop competitive applications such as gaming systems or systems software.
This guide is about programming in CPP. It covers the use of variables, data types, control statements, and many other concepts. Also, this guide covers some advanced topics like OOP concepts (object class inheritance), templates, and STL. Overall, reading this will help you develop skills as a beginner or assist in polishing your C++ skills.
Overview of C++
Developed by Bjarne Stroustrup in 1979, C++ works as a general-purpose programming language which was an extension of C language. It supports object-oriented programming and complex coding and provides flexible and efficient system programming. Both low-level and high-level programming is supported by C++. Therefore, it is used in designing applications that range from operating systems to video games.
C++ can be directly used on different types of hardware resources and provides a rich feature set. This makes it one of the most used and successful programming languages worldwide.
History of C++
In the table below, we have covered the history of C++.
Year
Event
1979
Bjarne Stroustrup begins work on “C with Classes”
1983
The name changed to C++
1998
The first standardised version, C++98, was released
2003
Minor update with C++03
2011
Major update with C++11, introducing many new features
2014
C++14 introduced new features like quoted strings, binary integer literals, etc.
2017
C++17 introduced new features like inline variables, etc.
2020
The latest update, C++20, brings significant changes and new features
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Key Features of C++
Some key features associated with C++ include the following:
Object-Oriented Programming: Important features like class, structures, objects, inheritance, polymorphism, encapsulation, and abstraction are supported by C++.
Performance: C++ delivers high performance due to its close-to-hardware properties.
Portability: With little or no changes in code written in C++, it works on various platforms.
Standard Library: A good number of useful functions for manipulating data structures, such as algorithms, are provided by default in C++.
Memory Management: C++ provides both automatic and manual memory management capabilities through dynamic allocation and deallocation.
Applications of C++
C++ is widely used to develop software for various industries, and we have covered some use cases below.
System Software: Operating systems, device drivers as well as embedded systems are built using C++.
Game Development: C++ helps in the gaming industry by developing game engines and high-performance graphics.
GUI Applications: Desktop applications with graphical user interfaces can be developed using C++.
Financial Systems: High-speed computations are required in most financial applications, which is why they mostly use C++.
Scientific Research: C++ is employed in simulations, real-time systems, and other scientific research applications.
Basics of C++
First C++ Program
Let’s jump onto writing a very simple “Hello, World!” program to the screen.
Example:
In this code, the first line includes the ‘iostream’ library using the ‘#include’ preprocessor. It is used to perform the input-output operations.
Next, we have defined the ‘main()’ method in the second line. This is where the compiler starts compiling the code.
The third line indicates the printing method in C++ to print the output ‘Hello, World!’ string in the output console. At last, we return the integer 0 to terminate the program.
Comments are used to explain the code and make it more readable. They are ignored by the compiler, so they don’t affect the program’s execution.
There are two types of comments in C++:
Single-line comments: Start with // and extend to the end of the line.
// This is a single-line comment
std::cout << “Hello, World!” << std::endl; // Prints a message
Multi-line comments: Start with /* and end with */. They can span multiple lines.
/* This is a multi-line comment
It can span multiple lines */
std::cout << “Hello, World!” << std::endl;
C++ Identifiers
Identifiers are names given to various elements in a program, such as variables, functions, arrays, and more. They are used to identify these elements within the code.
Here are the rules for naming identifiers in C++:
Identifiers can include letters (both uppercase and lowercase), digits, and underscores.
They must begin with a letter or an underscore.
Identifiers are case-sensitive (myVariable and myvariable are different).
Keywords cannot be used as identifiers.
Examples of valid identifiers:
int age;
float salary;
char first_name;
Examples of invalid identifiers:
int 1stNumber; // Cannot start with a digit
float my-salary; // Cannot contain hyphen
char class; // Cannot use a keyword
Variables and Constants in C++
C++ Variables
Variables are commonly used to store data during the execution of a program. Here data can be changed dynamically, and each variable holds a specific type of data it can hold.
Here’s how to declare and initialise variables in C++:
Here, ‘int’, ‘float’, ‘char’, etc., are the data types of the ‘age’, ‘salary’, and ‘grade’ variables, respectively.
C++ Constants
Constants are variables whose values cannot be changed once they are initialised. They are defined using the const keyword.
Here’s how to declare constants in C++:
const int MAX_AGE = 100; // Constant integer
const float PI = 3.14; // Constant float
const char NEWLINE = ‘n’; // Constant character
Using constants helps in making your code more readable and maintainable, as the value of the constant is set once and cannot be modified later.
Scope of C++ Variables
The scope of a variable refers to the region of a program where that variable can be accessed. In C++, there are two types of scopes:
Local Scope: These are the variables that are declared within a function or block having local scope. Thus, they can only be accessed from within that function or block.
Global Scope: Those variables that are declared outside all functions have global scope. Hence, they can be accessed from any part of the program.
C++ Static Variables
Static variables in C++ have a limited scope for the function where they are initialised and retain their value even after function execution is completed.
Here’s how to declare a static variable in a function:
We can see, in the output, the counter variable has retained value between function calls after it is initialised. Therefore, static variables are commonly used to maintain the state information between function calls.
Data Types in C++
Data types in C++ specify the type of data that a variable can hold. They are essential for defining the operations that can be performed on the data and the amount of memory allocated for the data.
In C++, data types can be broadly categorised into three types:
Primary Data Types
Derived Data Types
User-Defined Data Types.
Primary Data Types
Derived Data Types
User-Defined Data Types
int
Arrays
Structures (struct)
char
Pointers
Unions (union)
bool
References
Enumerations (enum)
float
Functions
Classes (class)
double
void
Type Casting in C++
Type casting involves converting one data type into another.
In C++, type casting falls into two categories – implicit and explicit casting.
Implicit Type Casting: Also called automatic type conversion, this kind of type casting is done by the compiler without any instruction from the programmer’s end. The compiler converts smaller data types into larger ones automatically so as to avoid data loss.
Example:
int a = 42;
double b = a; // Implicit conversion from int to double
Explicit Type Casting: Explicit type casting, also known as type conversion, requires the programmer to specify the type conversion. This is done using the cast operator.
Example:
double a = 42.56;
int b = (int)a; // Explicit conversion from double to int
Operators in C++
Operators are special symbols that perform operations on variables and values, which helps to manipulate data and variables. They provide a wide range of functions (from basic arithmetic to complex logic operators).
C++ provides a variety of operators, which can be categorised based on their functionality. Below is a table summarising the different types of operators available in C++.
Compare two values and return a boolean result (true or false)
Logical Operators
&&, ||, !
Perform logical operations (AND, OR, NOT)
Bitwise Operators
&, |, ^, ~,<<, >>
Perform operations on bits and bit patterns
Assignment Operators
=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, `
Assign values to variables and modify them
Increment/Decrement Operators
++, —
Increase or decrease the value of a variable by one
Conditional (Ternary) Operator
? :
Return one of two values depending on a condition
Comma Operator
,
Separate two or more expressions
Member Access Operators
. , ->
Access members of a class or structure
Pointer Operators
*, &
Operate on pointer variables
Type Cast Operator
(type)
Convert a variable from one type to another
sizeof Operator
sizeof
Return the size of a data type or variable
Other Operators
::, .*, ->*, new, delete
Miscellaneous operators for various purposes
Input/Output in C++
Input and output (I/O) operations in C++ are essential for interacting with users and external systems. The C++ Standard Library provides a set of functions and objects to handle I/O operations efficiently.
Input using cin
The cin object is used to read input from the standard input device, usually the keyboard. The >> operator is used to extract the data from cin.
Example:
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You entered: " << age << std::endl;
return 0;
}
Output using cout
The cout object is used to print output to the standard output device, usually the screen. The << operator is used to send the data to cout.
The Control statements in C++ are mainly used to manage the flow of execution of a program. Features like repeating operations, jumping to different parts of code, task-making decisions, etc. are primary tasks of control statements.
C++ Decision Making
Depending upon a specific condition (true or false), the decision-making helps to execute such conditions. If, else, switch are the most commonly used decision-making statements in C++.
if statement: Code will be executed only if the specified condition is true.
else if statement: It adds a condition to check if the initial if condition returns false.
else statement: Executed when none of the above conditions returned true.
switch statement: A switch statement supports multiple decision statements at once and also supports jumping to multiple paths based upon its value.
Example of the if-else statement:
Here, we have printed different statements using the value of the age variable and checking if it is greater than or equal to 18
#include <iostream>
int main() {
int age = 10;
if (age >= 18) {
std::cout << "You are an adult." << std::endl;
} else {
std::cout << "You are not an adult." << std::endl;
}
return 0;
}
Output:
You are not an adult.
C++ Loops
C++ loop is one of the most important key features in the entire programming language because it helps to repeat a particular block of code in some finite number. Three types of loops are mentioned below
for loop: When the number of iterations is known, a for loop is used.
while loop: This loop runs infinite times and breaks until and unless a condition becomes false. It is mainly used when there is no knowledge of a specific number of iterations.
do-while loop: This is almost similar to a while loop with one change, i.e. an initial condition is checked before running that code block in repetition. Hence, it is a control flow statement that stops execution depending upon a given boolean condition.
Example of for loop:
In the code below, we use the for-loop to print 1 to 5 values.
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
std::cout << "Iteration: " << i << std::endl;
}
return 0;
}
Functions in C++ perform a specific given task using inputs, arguments, parameters, type of data types, etc., and return an output based upon the code block conditions. Functions mainly help in making reusable code, which is both time-saving and makes code organisation friendly.
Defining and Calling Functions
Here’s what you need to do for defining and calling functions.
#include <iostream>
int add(int a, int b) { // Function definition
return a + b;
}
int main() {
int result = add(5, 3); // Function call
std::cout << "The sum is: " << result << std::endl;
return 0;
}
This is the basic example of a function that adds two numbers by specifying return type, name, and parameters. In this, int add (int a, int b) is a function taking two integers a and b, returning its sum.
Inline Functions: You can define inline functions using the inline keyword so that the compiler inserts the function’s code directly at the end of each call.
Lambda Functions: These are the anonymous functions defined through the [] syntax. They are introduced in c++11 and often used for short snippets of code.
Example of a lambda function:
In the given code below, the ‘add’ function adds two integers and returns their sum. Lambda functions are used for quick temporary function creation and do not need a separate name definition.
#include <iostream>
int main() {
auto add = [](int a, int b) -> int {
return a + b;
};
std::cout << "The sum using lambda is: " << add(4, 3) << std::endl;
return 0;
}
Pointers and References in C++
Pointers in C++ are mainly used for efficient memory allocation and manipulation. Hence, they are among the most powerful features in C++.
Pointers
In brief, the pointers are the variables that can store the memory address of another variable. Thus, they are used for dynamic memory allocation, accessing array elements, and passing large structures or arrays to functions efficiently.
Declaring and Using Pointers: To declare a pointer, you use the asterisk (*) symbol. To access the value at the memory address stored in the pointer, you use the dereference operator (&).
Example:
In this example, ptr is a pointer to var. The & operator is used to get the address of var, and *ptr is used to get the value at that address.
#include <iostream>
int main() {
int var = 42;
int* ptr = &var; // Pointer to the memory address of var
std::cout << "Value of var: " << var << std::endl;
std::cout << "Address of var: " << ptr << std::endl;
std::cout << "Value at address ptr: " << *ptr << std::endl;
return 0;
}
Output:
Value of var: 42
Address of var: 0x7ffe399b6c94
Value at address ptr: 42
References
Alternative to pointers, a reference is a way to create an alias for another variable. References are generally safer and easier due to the fact that they do not require dereferencing, and they cannot be null.
Declaring and Using References: Here, you should use the ampersand (&) symbol for the initialisation of reference, and then it cannot be changed to refer to another variable.
Arrays are used to store multiple values of the same type in a single variable. They provide a way to organise data efficiently and allow easy access to each element.
Declaring and Initializing Arrays
One of the most common tasks is declaring and initialising arrays, and it can be done by specifying the type, name, and number of elements in square brackets.
Example:
In the given example, an array of 5 integers is created, named ‘numbers’. The total size of the array while initialisation is 3.
Strings in C++ are sequences of characters used to represent text. There are multiple ways to handle strings which include C-style Strings and the std::string class from its library.
C-Style Strings: they are arrays of characters ending with a null character (0). They are the traditional way of handling strings in C and C++.
std::string Class: The std::string class brings a more convenient way to work with strings through many built-in functions for string manipulation.
Creating and Using std::string:
In this example, the greeting is a std::string object. We demonstrate concatenation, getting the length of the string and outputting the string.
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, World!"; // std::string initialization
std::cout << "Greeting: " << greeting << std::endl;
// String concatenation
std::string name = "Alice";
std::string personalizedGreeting = greeting + " My name is " + name + ".";
std::cout << personalizedGreeting << std::endl;
// String length
std::cout << "Length of greeting: " << greeting.length() << std::endl;
return 0;
}
Output:
Greeting: Hello, World!
Hello, World! My name is Alice.
Length of greeting: 13
Structures and Union in C++
Structures can be defined as the data types which allow the grouping of different structures and unions using a single name so that it can create complex data..
Structures: Structures (struct) in C++ are used to group variables of different types together. Each variable in a structure is called a member.
Defining and Using Structures:
In this example, the Person structure groups together a string (name), an integer (age), and a float (height) variables. We create an instance of Person, assign values to its members, and print them.
#include <iostream>
// Define a structure
struct Person {
std::string name;
int age;
};
int main() {
// Create a structure variable
Person person1;
person1.name = "Alice";
person1.age = 30;
// Accessing structure members
std::cout << "Name: " << person1.name << std::endl;
std::cout << "Age: " << person1.age << std::endl;
return 0;
}
Output:
Name: Alice
Age: 30
Unions: Note that the unions in C++ are likely similar to the structures but with key differences. Hence, at a time, a union can hold only one of its members.
Dynamic Memory Management in C++
Dynamic memory management in C++ involves allocating and deallocating memory during runtime. This allows for flexible memory usage and efficient management of resources. The primary functions used for dynamic memory management are new and delete.
Allocating Memory with new: This can be used to allocate memory dynamically for a single variable or an array of variables. It returns a pointer to the allocated memory.
Example:
int* ptr = new int; // Allocates memory for a single integer
int* arr = new int[10]; // Allocates memory for an array of 10 integers
Deallocating Memory with delete: To deallocate the previously allocated memory with the new one, the delete operator is used, which is also important to prevent memory loss.
Example:
delete ptr; // Deallocates memory for the single integer
delete[] arr; // Deallocates memory for the array of integers
Object-Oriented Programming in C++
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure software programs. C++ supports OOP, which helps in organising complex programs into simpler, reusable components.
Classes and Objects
Classes are user-defined types that represent blueprints for objects. Objects are instances of classes.
Example:
Here, a Car is a class formed with two attributes (brand and year) and a method (displayInfo). myCar is an object of the Car class.
#include <iostream>
class Car {
public:
std::string brand;
int year;
void displayInfo() {
std::cout << "Brand: " << brand << ", Year: " << year << std::endl;
}
};
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
myCar.displayInfo();
return 0;
}
Output:
Brand: Toyota, Year: 2020
Encapsulation
Encapsulation restricts the direct access to some of the object’s components and can bundle data in a single unit (class) to prevent data modification.
Inheritance
Inheritance is the best example of code reusability, where a child class (subclass) is derived from its parent class (superclass) using their components. This promotes code reliability and also helps in assessing complex coding.
Polymorphism
Polymorphism allows its methods to conduct different things based on the property of the object it is acting upon. This includes compile-time polymorphism (method overloading) and runtime polymorphism (method overriding).
Abstraction
As the name suggests, abstraction is used to abstract or hide complex implementation details in a complex code. Hence, it helps in reducing the overall complexity of the program.
Function Overloading in C++
To have the same name with different parameters in any function, function overloading is used.
Example:
For example, the print function below is overloaded so that it can handle both integer and double inputs.
#include <iostream>
void print(int i) {
std::cout << "Integer: " << i << std::endl;
}
void print(double d) {
std::cout << "Double: " << d << std::endl;
}
int main() {
print(10); // Calls the integer version
print(5.5); // Calls the double version
return 0;
}
Output:
Integer: 10
Double: 5.5
Operator Overloading in C++
Operator overloading in C++ allows developers to define custom behaviour for operators when they are used with user-defined types (classes). This makes objects of these classes behave more like built-in types.
Example:
In this example, the + operator is overloaded to add two Complex numbers. This allows the + operator to be used with complex objects just like with built-in types.
The basic need for virtual functions in C++ is to ensure that the function called is correct, regardless of the type of reference or pointer used to call. Hence, virtual functions can be overridden in derived classes. This allows for dynamic (runtime) polymorphism, enabling more flexible and reusable code.
Rules for Virtual Functions
Declaration: Use the virtual keyword in the base class.
Override: In the derived class, the function signature must match the base class’s virtual function.
Base Class Pointer: Using a base class pointer or reference, call the overridden function.
Destructors: Every virtual function must have a virtual destructor to avoid memory leakage and properly clean up derived class objects.
Exception Handling in C++
In C++, the basic way to manage errors and all exceptions is to use exception handling. It helps to maintain the normal flow of the program, simultaneously dealing with exceptions and unexpected errors.
Key Components
Try block: Encloses the code that may throw an exception.
Catch block: Catches and handles the exception.
throw keyword: Used to throw an exception.
Example:
#include <iostream>
int main() {
try {
int divisor = 0;
if (divisor == 0) {
throw std::runtime_error("Division by zero error");
}
int result = 10 / divisor;
std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
In this example:
The try block contains code that may cause an exception.
Throw keyword throws an exception whenever someone attempts a division by zero.
The catch block handles the exception, preventing the program from crashing.
Files and Streams in C++
Files and streams in C++ handle input and output operations with external files, enabling data storage and retrieval.
C++ uses classes from the <fstream> library for file operations:
ifstream: For reading from files.
ofstream: For writing to files.
fstream: For both reading and writing.
Key Concepts
Concept
Description
Opening Files
Use the open method to open a file.
Closing Files
Use the close method to close a file and release resources.
Reading
Use ifstream with >>, getline, or read.
Writing
Use ofstream with << or write.
File Status
is_open(), eof(), fail() methods to check file status.
File Modes
Specify mode (e.g., ios::in, ios::out, ios::app) while opening a file.
So you can effectively manage file operations in C++, using these classes and methods.
Templates in C++
Templates in C++ provide a powerful mechanism for creating generic and reusable code. They allow functions and classes to operate with different data types without being rewritten for each type.
Function Templates
Function templates enable you to define a generic function that works with any data type. The actual data type is specified when the function is called.
Syntax:
template <typename T>
T functionName(T parameter) {
// Function implementation
}
Class Templates
Class templates allow you to define a generic class. Similar to function templates, the actual data type is specified when an object of the class is created.
Syntax:
template <typename T>
class ClassName {
public:
T member;
// Class implementation
};
STL in C++
Ever wondered about an inbuilt set of template classes and functions to provide your code with common data structure codes? The Standard Template Library (STL) offers ready-to-use components or reusable code snippets in C++ to make your work easy.
Key Components of STL
Component
Description
Containers
Classes that store collections of objects (e.g., vector, list, map).
Algorithms
Functions for processing sequences of elements (e.g., sort, find, copy).
Iterators
Objects that enable traversal of container elements (e.g., begin(), end()).
Functors
Objects that can be used as function pointers (e.g., for custom operations in algorithms).
Iterators in C++
Iterators in C++ allow multiple traversals through the same code block by providing a common interface for iterating different types of elements throughout the function.
Types of Iterators
Input Iterators: Read elements from a sequence.
Output Iterators: Write elements to a sequence.
Forward Iterators: Traverse a sequence in a single pass (read/write).
Bidirectional Iterators: These iterators can traverse a sequence in both forward and backward directions.
Random Access Iterators: Directly access any element within a sequence.
Example of Using Iterators:
In this example, There is an iterator for the vector<int> container. When we use the for loop, it uses the iterator to traverse and print each element in a numbers vector simultaneously.
Before the actual compilation of the code, the preprocessor directives are used, providing instructions to the compiler on what to preprocess in the source code before compiling. To start a preprocessor directive, you can use the # symbol, which can also be used to include files, define constants, and compile conditionally.
Key Preprocessor Directives
Directive
Description
Syntax
#include
It includes the contents of a file in the current file.
#include <filename> or #include “filename”
#define
Defines macros or symbolic constants.
#define NAME value
#undef
Undefines a previously defined macro.
#undef NAME
#if, #elif, #else, #endif
These are the conditional compilation directives which include or exclude parts of the code based on conditions.
It provides additional information to the compiler, such as suppressing warnings or optimising code.
#pragma di
C vs C++
C is a procedural programming language that does not support classes. On the other hand, C++ is an extension of C that includes object-oriented features.
Feature
C
C++
Programming Paradigm
Procedural
Procedural and Object-Oriented
Data Security
Less secure due to global data
More secure with encapsulation
Inheritance
Not supported
Supported
Polymorphism
Not supported
Supported
Function Overloading
Not supported
Supported
Standard Library
Limited
Extensive with STL (Standard Template Library)
Memory Management
Manual using malloc and free
Automatic with constructors and destructors
Complexity
Simpler but less powerful
More complex but more powerful
C++ vs Java
Both C++ and Java have their own benefits that users can use for different purposes. C++ can hold more complex code in object-oriented programming and also help in increasing performance efficiency. While Java is designed for portability and ease of use.
Feature
C++
Java
Platform Dependency
Platform-dependent
Platform-independent (runs on JVM)
Memory Management
Manual with pointers
Automatic garbage collection
Multiple Inheritance
Supported
Not supported (interfaces used instead)
Performance
Generally faster
Generally slower due to JVM overhead
Syntax
Closer to hardware, more complex
Simpler, more abstracted
Standard Library
Extensive (STL)
Extensive (Java API)
Use Cases
System/software development, game development
Web applications, enterprise solutions
Compilation
Compiled to machine code
Compiled to bytecode and interpreted by JVM
Advantages and Disadvantages of C++
C++ offers a balance of high performance and rich feature sets but comes with complexity and potential pitfalls.
Advantages
Disadvantages
High performance
Complex syntax and steep learning curve
Object-oriented features
Manual memory management can lead to errors
Extensive standard library (STL)
Lack of built-in garbage collection
Flexibility and control over system resources
Potential for security issues with pointers
Suitable for system/software development, game development
Larger executable size compared to some other languages
Rich features like function and operator overloading
Difficulty in debugging and maintenance
Conclusion
C++ is thought to be a versatile and powerful programming language that builds upon the C foundation. It has robust features like object-oriented programming and strong standard libraries. C++ can be a very high-performance programming language, making it perfect to use for complex applications like system software development or game development. You can learn more about functions, pointers, control statements, data types, STL, etc. through this article.
FAQs
What is the main difference between C and C++?
The main difference is that C++ supports object-oriented programming while C supports procedural programming.
How does C++ handle memory management?
In this context, the principal approach used by C++ is manual memory management with new and delete, but can also provide explicit memory management through constructors and destructors.
Can we use C++ in game development?
Yes, due to its speed capabilities and flexibility, it’s widely employed in game development.
What are some common uses of the Standard Template Library (STL) in C++?
STL helps in managing data structures and algorithms, along with iterators, making it a combined reusable general template that can be the base of any starting function or defining object.
How does exception handling work in C++?
In C++, exception handling lets you catch errors gracefully at runtime. You can use try, catch, and finally block to handle exceptions.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.