Learn C++ Programming from Beginner to Advanced
Master C++ from scratch with practical examples, interview questions, programming exercises, modern C++ concepts, object-oriented programming, STL, and real-world applications. This complete tutorial is designed for students, beginners, software developers, and coding interview preparation.
What is C++ Programming?
C++ is one of the world's most powerful, efficient, and widely used programming languages. It was developed as an extension of the C programming language while introducing object-oriented programming concepts. Today, C++ is used to build operating systems, desktop applications, game engines, browsers, embedded systems, robotics software, artificial intelligence libraries, and high-performance applications.
Unlike many modern programming languages, C++ provides complete control over system resources and memory management. This allows developers to build extremely fast and optimized software.
C++ is a general-purpose, compiled, object-oriented programming language that supports procedural, generic, and functional programming paradigms.
History of C++
The history of C++ begins with the C programming language. Although C was fast and powerful, it lacked several software engineering features such as classes, inheritance, encapsulation, and polymorphism. To overcome these limitations, Danish computer scientist Bjarne Stroustrup started working on "C with Classes" at Bell Laboratories in 1979. The language was officially renamed C++ in 1983.
| Year | Development |
|---|---|
| 1972 | C Programming Language developed by Dennis Ritchie. |
| 1979 | Bjarne Stroustrup started C with Classes. |
| 1983 | Language renamed to C++. |
| 1985 | First commercial release. |
| 1998 | ISO Standard C++98 released. |
| 2011 | Modern C++ begins with C++11. |
| 2020 | C++20 introduced Concepts, Modules and Coroutines. |
| 2023 | C++23 released with many improvements. |
Why Learn C++?
Learning C++ provides a strong foundation in programming and computer science. It helps developers understand how software interacts with hardware while improving problem-solving skills.
⚡ High Performance
C++ programs compile directly into machine code, making them extremely fast.
🎮 Game Development
Professional game engines like Unreal Engine are primarily written in C++.
💼 Career Opportunities
Top technology companies actively hire C++ developers for system programming, embedded software, AI, and backend engineering.
🏆 Competitive Programming
Most coding competitions recommend C++ because of its speed and Standard Template Library (STL).
Google Chrome, Adobe Photoshop, Microsoft Office, Unreal Engine, MySQL, Blender, and many financial trading systems use C++ in their core components.
Key Features of C++
Object-Oriented Programming
Supports classes, objects, inheritance, abstraction, encapsulation, and polymorphism.
Portable
Programs can run on Windows, Linux, and macOS with minimal modifications.
Rich Standard Library
Includes STL containers, algorithms, iterators, strings, smart pointers, and utilities.
Dynamic Memory
Developers can allocate and release memory using new and delete.
Multi-Paradigm
Supports procedural, object-oriented, generic, and functional programming.
Fast Execution
Compiled programs execute significantly faster than interpreted languages in many scenarios.
- ✔ What is C++
- ✔ History of C++
- ✔ Why Learn C++
- ✔ Features of C++
Advantages of C++ Programming Language
C++ has remained one of the most popular programming languages for decades because it provides a perfect balance between performance, flexibility, and control. Many professional developers choose C++ when they need software that is fast, reliable, and resource-efficient.
🚀 1. Extremely Fast Performance
C++ is a compiled language, which means the source code is converted directly into machine code. This allows applications to execute faster compared to many interpreted languages.
For this reason, C++ is widely used in game engines, operating systems, browsers, and financial applications where speed is critical.
🧠 2. Complete Memory Control
C++ provides direct control over memory allocation and deallocation. Developers can efficiently manage system resources using pointers, references, and dynamic memory techniques.
♻ 3. Code Reusability
Object-oriented programming features like classes, inheritance, and polymorphism allow developers to write reusable and maintainable code.
🌎 4. Platform Independent
A properly written C++ program can run on multiple platforms including Windows, Linux, and macOS with minimal changes.
📚 5. Powerful Standard Library
The C++ Standard Library provides ready-made solutions for data structures, algorithms, input/output operations, strings, and more.
🏆 6. Best for Competitive Programming
Competitive programmers prefer C++ because of its execution speed and powerful STL features like vectors, maps, sets, and algorithms.
Disadvantages of C++
Although C++ is a powerful language, beginners should understand some challenges before learning it.
| Challenge | Explanation |
|---|---|
| Complex Syntax | C++ contains many advanced concepts like pointers, templates, and memory management, which require time to master. |
| Manual Memory Management | Developers must carefully manage memory. Incorrect handling may cause memory leaks or crashes. |
| Long Compilation Time | Large C++ projects may take longer to compile compared to simpler languages. |
| Steep Learning Curve | Beginners need patience because C++ combines low-level and high-level programming concepts. |
| Error Handling | Some programming errors, especially pointer-related problems, can be difficult to debug. |
Do not try to memorize every C++ feature at the beginning. First understand programming logic, syntax, functions, and object-oriented concepts. Advanced topics become easier with practice.
Applications of C++ Programming
C++ is used in many industries because it provides high performance and low-level hardware control.
💻 Operating Systems
Many operating system components and system-level tools are developed using C++ because they require direct hardware interaction and high speed.
🎮 Game Development
C++ is one of the most important languages in gaming. Popular game engines use C++ because games require maximum performance.
Examples:
• Unreal Engine
• Unity engine components
• AAA games
🌐 Web Browsers
Modern browsers use C++ for performance-critical components such as rendering engines and JavaScript engines.
🤖 Robotics
Robotics systems require real-time processing, making C++ a preferred choice for robot control software.
🚗 Automotive Industry
Modern vehicles use C++ for embedded systems, autonomous driving software, and electronic control units.
🛰 Aerospace
High-performance aerospace software often uses C++ because reliability and speed are extremely important.
💰 Banking and Finance
Financial trading systems use C++ because they require extremely low response times.
🧬 Artificial Intelligence
Many AI frameworks use C++ internally for performance optimization even though Python is popular for AI development.
Companies That Use C++
Many leading technology companies use C++ for their high-performance products and services.
| Company | Usage |
|---|---|
| Search engine infrastructure, Chrome browser components, performance-critical systems | |
| Microsoft | Windows components, Office applications, development tools |
| Adobe | Photoshop, Illustrator, Creative Cloud applications |
| Amazon | High-performance backend services and infrastructure |
| Meta | Large-scale systems, databases, and performance applications |
| NVIDIA | GPU drivers, graphics technologies, CUDA ecosystem |
Career Opportunities After Learning C++
Learning C++ can open opportunities in many software engineering fields.
👨💻 Software Developer
Develop desktop applications, system software, and backend solutions.
🎮 Game Developer
Create game engines, graphics systems, and high-performance games.
⚙ Embedded Engineer
Develop software for microcontrollers, IoT devices, and automotive systems.
🧮 Algorithm Engineer
Work on optimization, data structures, and complex problem solving.
🤖 Robotics Engineer
Build intelligent machines and automation systems.
🔐 System Programmer
Develop operating system components, security tools, and low-level software.
C++ Learning Roadmap
| Level | Topics |
|---|---|
| Beginner | Syntax, Variables, Data Types, Operators, Conditions, Loops, Functions |
| Intermediate | Arrays, Strings, Pointers, Structures, Classes, Objects, OOP Concepts |
| Advanced | Templates, STL, Exception Handling, File Handling, Memory Management |
| Professional | Modern C++, Design Patterns, Optimization, System Programming |
- ✔ What is C++
- ✔ History of C++
- ✔ Features of C++
- ✔ Advantages and Disadvantages
- ✔ Applications
- ✔ Career Opportunities
Chapter 4: Variables, Data Types and Constants in C++
In the previous chapters, we learned about the basic structure of a C++ program, compiler, and how to write our first C++ code. In this chapter, we will learn one of the most important concepts in C++ programming: variables, data types, and constants.
Every programming language works with data. To store and manipulate data, we need variables and different types of data types.
What is a Variable in C++?
A variable is a container that stores a value inside the computer's memory. Each variable has a name, data type, and value.
Example:
#include <iostream>
using namespace std;
int main()
{
int age = 20;
cout << age;
return 0;
}
Output:
In the above example:
- int → Data type
- age → Variable name
- 20 → Value stored inside variable
Rules for Naming Variables in C++
While creating variables, we must follow some important rules.
- Variable name can contain letters, digits and underscore.
- Variable name cannot start with a digit.
- Spaces are not allowed inside variable names.
- C++ keywords cannot be used as variable names.
- C++ is case-sensitive, so age and Age are different variables.
Valid Variable Names
int age;
float student_marks;
char grade;
int number1;
Invalid Variable Names
int 1number; // Cannot start with number
float student marks; // Space not allowed
int class; // Keyword cannot be used
Data Types in C++
A data type specifies what type of data a variable can store. C++ provides different types of data types depending on the requirement.
Types of Data Types in C++
1. Fundamental Data Types
Basic built-in data types provided by C++.
- int
- float
- double
- char
- bool
- void
2. Derived Data Types
- Array
- Pointer
- Function
3. User Defined Data Types
- Structure
- Class
- Union
- Enumeration
Fundamental Data Types Explained
1. Integer Data Type (int)
The int data type is used to store whole numbers without decimal values.
int marks = 95;
cout << marks;
Example values:
2. Float Data Type
The float data type stores decimal numbers with single precision.
float price = 99.50;
cout << price;
3. Double Data Type
Double stores decimal values with higher precision compared to float.
double pi = 3.1415926535;
cout << pi;
4. Character Data Type (char)
The char data type stores a single character.
char grade = 'A';
cout << grade;
Characters must be written inside single quotes.
5. Boolean Data Type (bool)
Boolean stores only two values:
- true
- false
bool isStudent = true;
cout << isStudent;
Output:
In C++, true represents 1 and false represents 0.
Size of Data Types in C++
The memory size of data types depends on the compiler and system architecture.
| Data Type | Typical Size |
|---|---|
| char | 1 byte |
| int | 4 bytes |
| float | 4 bytes |
| double | 8 bytes |
| bool | 1 byte |
Using sizeof() Operator
C++ provides the sizeof() operator to find the memory occupied by a variable.
#include <iostream>
using namespace std;
int main()
{
cout << sizeof(int);
return 0;
}
Output may be:
Constants in C++
A constant is a value that cannot be changed during program execution.
We use the keyword const to create constants.
#include <iostream>
using namespace std;
int main()
{
const float PI = 3.14;
cout << PI;
return 0;
}
Variable Initialization Methods in C++
1. Traditional Initialization
int number = 10;
2. C++11 Uniform Initialization
int number {10};
3. Declaration First, Assignment Later
int age;
age = 25;
Complete Example Program
#include <iostream>
using namespace std;
int main()
{
string name = "Rahul";
int age = 21;
float height = 5.8;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Height: " << height;
return 0;
}
Chapter Summary
- Variables are used to store data in memory.
- Data types define what type of value a variable can store.
- C++ supports fundamental, derived and user-defined data types.
- Constants are fixed values that cannot be changed.
- sizeof() helps to find memory size of data types.
Chapter 5: Operators in C++ Programming
Operators are one of the most important concepts in C++ programming. Operators are special symbols that perform operations on variables and values.
For example, the + operator performs addition, the - operator performs subtraction, and the * operator performs multiplication.
10 + 5 = 15
Here + is an operator, and 10 and 5 are operands.
Types of Operators in C++
C++ provides different types of operators for performing various operations.
1. Arithmetic Operators
Used for mathematical calculations.
2. Relational Operators
Used for comparing two values.
3. Logical Operators
Used for logical decision making.
4. Assignment Operators
Used for assigning values.
5. Increment and Decrement Operators
Used to increase or decrease values.
6. Bitwise Operators
Used for bit-level operations.
1. Arithmetic Operators in C++
Arithmetic operators are used to perform basic mathematical calculations.
| Operator | Name | Example |
|---|---|---|
| + | Addition | a+b |
| - | Subtraction | a-b |
| * | Multiplication | a*b |
| / | Division | a/b |
| % | Modulus (remainder) | a%b |
Arithmetic Operator Example
#include <iostream>
using namespace std;
int main()
{
int a = 20;
int b = 5;
cout << "Addition: " << a+b << endl;
cout << "Subtraction: " << a-b << endl;
cout << "Multiplication: " << a*b << endl;
cout << "Division: " << a/b << endl;
cout << "Remainder: " << a%b;
return 0;
}
Output:
Subtraction: 15
Multiplication: 100
Division: 4
Remainder: 0
2. Relational Operators in C++
Relational operators are used to compare two values. They always return either true or false.
| Operator | Meaning |
|---|---|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
Example
#include <iostream>
using namespace std;
int main()
{
int a=10;
int b=20;
cout << (a<b);
return 0;
}
Output:
Because 10 is less than 20, the condition is true.
3. Logical Operators in C++
Logical operators are mainly used with conditions. They are commonly used in decision-making statements like if, while and for loops.
| Operator | Name | Description |
|---|---|---|
| && | Logical AND | True when both conditions are true |
| || | Logical OR | True when any one condition is true |
| ! | Logical NOT | Reverses the result |
Logical AND Example
int age = 25;
if(age>18 && age<60)
{
cout<<"Eligible";
}
Both conditions must be true for AND operator.
4. Assignment Operators in C++
Assignment operators are used to assign values to variables.
| Operator | Example | Equivalent |
|---|---|---|
| = | a=10 | Assign value |
| += | a+=5 | a=a+5 |
| -= | a-=5 | a=a-5 |
| *= | a*=5 | a=a*5 |
| /= | a/=5 | a=a/5 |
5. Increment and Decrement Operators
Increment and decrement operators are used to increase or decrease values by one.
Increment Operator (++):
int a=5;
a++;
cout<<a;
Output:
Decrement Operator (--):
int a=5;
a--;
cout<<a;
Output:
Pre Increment and Post Increment
Pre Increment
Value increases first, then it is used.
int a=5;
cout<<++a;
Output:
Post Increment
Current value is used first, then it increases.
int a=5;
cout<<a++;
Output:
6. Bitwise Operators in C++
Bitwise operators perform operations directly on binary values.
| Operator | Name |
|---|---|
| & | Bitwise AND |
| | | Bitwise OR |
| ^ | Bitwise XOR |
| ~ | Bitwise NOT |
| << | Left Shift |
| >> | Right Shift |
Bitwise Example
int a=5;
int b=3;
cout<<(a & b);
Binary representation:
3 = 011
AND = 001
Answer = 1
Operator Precedence in C++
When multiple operators are used in an expression, C++ follows operator precedence rules.
| Priority | Operators |
|---|---|
| 1 | () |
| 2 | *, /, % |
| 3 | +, - |
| 4 | Assignment = |
Chapter Summary
- Operators perform operations on data.
- Arithmetic operators are used for calculations.
- Relational operators compare values.
- Logical operators work with conditions.
- Assignment operators store values.
- Increment and decrement change values by one.
- Bitwise operators work on binary data.
Chapter 6: Input and Output in C++ Programming (cin, cout, getline)
Input and output are essential parts of every programming language. A program needs input from the user to perform operations and it needs output to display the results.
In C++, input and output operations are handled using the iostream header file.
#include <iostream>
This header file contains the definitions of input and output objects like cin, cout, and other stream functions.
C++ Output Statement (cout)
The cout object is used to display output on the screen. It is called the standard output stream.
Syntax:
cout << value;
Example:
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome to C++ Programming";
return 0;
}
Output:
Displaying Variables Using cout
We can directly print the values stored inside variables using cout.
#include <iostream>
using namespace std;
int main()
{
int age = 20;
cout << age;
return 0;
}
Output:
Printing Multiple Values
Multiple values can be printed by using multiple insertion operators <<.
#include <iostream>
using namespace std;
int main()
{
string name="Alex";
int age=25;
cout << "Name: " << name << endl;
cout << "Age: " << age;
return 0;
}
Output:
Age: 25
New Line in C++
There are two common ways to create a new line in C++.
1. Using endl
cout << "Hello" << endl;
cout << "World";
Output:
World
2. Using Escape Sequence \n
cout << "Hello\nWorld";
Output:
World
C++ Input Statement (cin)
The cin object is used to take input from the user. It is called the standard input stream.
Syntax:
cin >> variable;
Example:
#include <iostream>
using namespace std;
int main()
{
int number;
cout<<"Enter a number: ";
cin>>number;
cout<<"You entered: "<<number;
return 0;
}
Output:
You entered: 50
Taking Multiple Inputs
C++ allows us to take multiple inputs in a single statement.
int a,b;
cin>>a>>b;
Example:
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter two numbers: ";
cin>>a>>b;
cout<<"Sum = "<<a+b;
return 0;
}
Output:
Sum = 30
Taking String Input in C++
There are two ways to take string input in C++:
- Using cin
- Using getline()
1. Using cin with Strings
string name;
cin>>name;
The cin statement stops reading when it finds a space.
Example:Stored: John
2. Using getline()
The getline() function is used to read complete lines including spaces.
#include <iostream>
using namespace std;
int main()
{
string fullName;
cout<<"Enter your name: ";
getline(cin,fullName);
cout<<fullName;
return 0;
}
Output:
John Smith
Difference Between cin and getline()
| cin | getline() |
|---|---|
| Reads until space | Reads complete line |
| Used for words and numbers | Used mainly for sentences |
| Uses >> | Uses getline() |
Escape Sequences in C++
Escape sequences are special characters used to perform formatting operations.
| Escape Sequence | Meaning |
|---|---|
| \n | New line |
| \t | Tab space |
| \\ | Backslash |
| \" | Double quote |
| \' | Single quote |
Example Program
#include <iostream>
using namespace std;
int main()
{
cout<<"C++\nProgramming";
return 0;
}
Output:
Programming
Formatted Output in C++
C++ provides formatting options to control how output appears.
Using setw()
setw() is used to set the width of output. It is available inside the iomanip header file.
#include <iomanip>
cout<<setw(10)<<"C++";
Using fixed and setprecision()
These are used for controlling decimal values.
#include <iomanip>
double price=45.6789;
cout<<fixed<<setprecision(2)<<price;
Output:
Complete Input and Output Program
#include <iostream>
using namespace std;
int main()
{
string name;
int age;
cout<<"Enter your name: ";
getline(cin,name);
cout<<"Enter your age: ";
cin>>age;
cout<<"\nStudent Details";
cout<<"\nName: "<<name;
cout<<"\nAge: "<<age;
return 0;
}
Chapter Summary
- cout is used to display output.
- cin is used to take input from users.
- getline() reads complete sentences with spaces.
- endl and \n are used for new lines.
- Escape sequences help format output.
- iomanip provides advanced output formatting functions.
Chapter 6: Object Oriented Programming (OOP) in C++
Object Oriented Programming (OOP) is one of the most important concepts in C++. It helps programmers write clean, reusable, secure, and maintainable code. C++ is called an object-oriented programming language because it supports classes and objects.
What is Object Oriented Programming?
Object Oriented Programming is a programming approach where programs are designed using objects and classes. Instead of focusing only on functions, OOP focuses on data and the operations performed on that data.
In real life, everything can be considered as an object. For example:
- Car
- Mobile Phone
- Student
- Bank Account
- Employee
Why do we need OOP?
Before OOP, programmers mainly used procedural programming. Large programs became difficult to manage because data and functions were separated.
OOP solves these problems by combining data and functions together.
Advantages of OOP
- Code reusability
- Better security of data
- Easy maintenance
- Real-world modelling
- Reduces code duplication
- Improves program organization
Main Concepts of OOP in C++
C++ mainly supports four important principles of Object Oriented Programming:
1. Encapsulation
Wrapping data and functions together into a single unit is called encapsulation.
2. Inheritance
The ability of one class to acquire properties of another class is called inheritance.
3. Polymorphism
One name having multiple behaviours is called polymorphism.
4. Abstraction
Showing only important information and hiding internal details is abstraction.
Classes in C++
A class is a blueprint or template used to create objects. It defines variables and functions that belong to an object.
Syntax of Class
class ClassName
{
// variables
// functions
};
Example:
#include <iostream>
using namespace std;
class Student
{
public:
string name;
int age;
};
int main()
{
Student s1;
s1.name = "Rahul";
s1.age = 20;
cout << s1.name << endl;
cout << s1.age;
return 0;
}
Output
Rahul 20
Objects in C++
An object is an instance of a class. A class only defines the structure, but an object occupies memory.
Example:
class Mobile
{
public:
string brand;
};
int main()
{
Mobile phone;
phone.brand="Samsung";
}
Class vs Object
| Class | Object |
|---|---|
| Blueprint of an object | Real instance of a class |
| Does not occupy memory | Occupies memory |
| Logical entity | Physical entity |
Access Specifiers in C++
Access specifiers control the visibility of class members. C++ provides three access specifiers.
| Specifier | Description |
|---|---|
| public | Members can be accessed anywhere |
| private | Members can be accessed only inside the class |
| protected | Members can be accessed inside class and derived classes |
Example of Public Access
#include <iostream>
using namespace std;
class Employee
{
public:
int salary;
};
int main()
{
Employee e;
e.salary = 50000;
cout << e.salary;
return 0;
}
Output
50000
Private Data Members
Private members cannot be directly accessed outside the class. They are used for data security.
#include <iostream>
using namespace std;
class Bank
{
private:
int balance;
public:
void setBalance(int amount)
{
balance = amount;
}
void showBalance()
{
cout << balance;
}
};
int main()
{
Bank b;
b.setBalance(10000);
b.showBalance();
return 0;
}
Output
10000
A class is a user-defined data type. An object is a variable of class type.
Summary of Chapter 6
- OOP is the foundation of modern C++ programming.
- Class is a blueprint for creating objects.
- Objects are instances of classes.
- Encapsulation combines data and functions.
- Access specifiers control data visibility.
Next Chapter
In the next chapter, we will learn: Constructors and Destructors in C++ with real-world examples and programs.
Chapter 7: Constructors and Destructors in C++
Constructors and destructors are very important concepts in C++ Object Oriented Programming. They are special member functions of a class that are automatically called during the creation and destruction of objects.
Constructors in C++, types of constructors, destructors in C++, default constructor, parameterized constructor, C++ OOP tutorial, learn C++ programming.
What is a Constructor in C++?
A constructor is a special function inside a class that is automatically executed when an object is created.
The main purpose of a constructor is to initialize the data members of a class.
A constructor has the same name as the class name and it does not have any return type.
Syntax of Constructor
class ClassName
{
public:
ClassName()
{
// constructor body
}
};
Example of Constructor in C++
#include <iostream>
using namespace std;
class Student
{
public:
Student()
{
cout << "Constructor called";
}
};
int main()
{
Student s;
return 0;
}
Output
Constructor called
When the object s is created, the constructor automatically executes.
Features of Constructor
- Constructor name must be the same as class name.
- Constructor does not have a return type.
- Constructor is automatically called.
- Constructors can be overloaded.
- They are mainly used for initialization.
Types of Constructors in C++
C++ mainly supports three types of constructors:
1. Default Constructor
A constructor without parameters is called a default constructor.
2. Parameterized Constructor
A constructor that accepts arguments is called a parameterized constructor.
3. Copy Constructor
A constructor that creates an object by copying another object.
1. Default Constructor in C++
A default constructor does not take any arguments.
#include <iostream>
using namespace std;
class Car
{
public:
Car()
{
cout << "Car object created";
}
};
int main()
{
Car c;
return 0;
}
Output
Car object created
2. Parameterized Constructor in C++
A parameterized constructor receives values during object creation.
Example:
#include <iostream>
using namespace std;
class Student
{
public:
string name;
int age;
Student(string n,int a)
{
name=n;
age=a;
}
void display()
{
cout<<name<<endl;
cout<<age;
}
};
int main()
{
Student s("Rahul",20);
s.display();
return 0;
}
Output
Rahul 20
3. Copy Constructor in C++
A copy constructor initializes one object using another object of the same class.
Syntax:
ClassName(const ClassName &object)
{
}
Example:
#include <iostream>
using namespace std;
class Number
{
public:
int value;
Number(int x)
{
value=x;
}
Number(Number &obj)
{
value=obj.value;
}
};
int main()
{
Number n1(100);
Number n2=n1;
cout<<n2.value;
return 0;
}
Output
100
Constructor Overloading in C++
Having multiple constructors with different parameters in the same class is called constructor overloading.
class Demo
{
public:
Demo()
{
}
Demo(int x)
{
}
Demo(int x,int y)
{
}
};
What is a Destructor in C++?
A destructor is a special member function that is automatically called when an object is destroyed.
Destructors are mainly used to release resources such as memory, files, and connections.
A destructor has the same name as the class but starts with a tilde (~) symbol.
Syntax of Destructor
class ClassName
{
public:
~ClassName()
{
// destructor code
}
};
Example of Destructor
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"Object Created"<<endl;
}
~Test()
{
cout<<"Object Destroyed";
}
};
int main()
{
Test t;
return 0;
}
Output
Object Created Object Destroyed
Difference Between Constructor and Destructor
| Constructor | Destructor |
|---|---|
| Used for initialization | Used for cleanup |
| Called when object is created | Called when object is destroyed |
| Can have parameters | Cannot have parameters |
| Can be overloaded | Cannot be overloaded |
| No special symbol | Uses ~ symbol |
Real World Example
Consider a bank account application.
- Constructor → Creates a new account and initializes customer details.
- Destructor → Closes files or releases memory when account object is removed.
Common Interview Questions
1. Can constructor return a value?
No. Constructors do not have return types.
2. Can destructor have parameters?
No. Destructors cannot accept parameters.
3. Can we create multiple constructors?
Yes. Constructor overloading is supported.
4. When is destructor called?
Automatically when an object goes out of scope or is deleted.
Chapter 7 Summary
- Constructor initializes objects automatically.
- Destructor cleans resources automatically.
- C++ supports default, parameterized, and copy constructors.
- Constructors can be overloaded.
- Destructor uses the ~ symbol.
Next Chapter
In the next chapter, we will learn: Inheritance in C++ – Types, Examples, Advantages, and Real-Time Usage
Chapter 8: Inheritance in C++ - Types, Examples and Real-World Usage
Inheritance is one of the most important concepts of Object Oriented Programming (OOP) in C++. It allows one class to acquire the properties and behaviours of another class.
Inheritance helps developers create reusable and organized code by avoiding repetition.
Inheritance in C++, types of inheritance in C++, C++ OOP concepts, single inheritance, multiple inheritance, multilevel inheritance, learn C++ programming.
What is Inheritance in C++?
Inheritance is a mechanism where a new class can reuse the data members and member functions of an existing class.
The existing class is called the Base Class or Parent Class.
The new class is called the Derived Class or Child Class.
Example of Real-World Inheritance
A vehicle is a general category. Cars, bikes, and trucks inherit common properties from vehicles.
- Vehicle → Base Class
- Car → Derived Class
Syntax of Inheritance
class DerivedClass : access_specifier BaseClass
{
// derived class members
};
Example:
class Animal
{
};
class Dog : public Animal
{
};
Why do we use Inheritance?
- Code reusability
- Reduces duplicate code
- Improves program structure
- Makes code easier to maintain
- Supports hierarchical classification
Types of Inheritance in C++
C++ supports five major types of inheritance:
1. Single Inheritance
One derived class inherits from one base class.
2. Multiple Inheritance
One derived class inherits from multiple base classes.
3. Multilevel Inheritance
A class is derived from another derived class.
4. Hierarchical Inheritance
Multiple derived classes inherit from one base class.
5. Hybrid Inheritance
Combination of two or more inheritance types.
1. Single Inheritance in C++
When one child class inherits from one parent class, it is called single inheritance.
#include <iostream>
using namespace std;
class Animal
{
public:
void eat()
{
cout<<"Animal eats"<
Output
Animal eats
Dog barks
2. Multiple Inheritance in C++
When one derived class inherits from more than one base class, it is called
multiple inheritance.
#include <iostream>
using namespace std;
class Father
{
public:
void house()
{
cout<<"Father house";
}
};
class Mother
{
public:
void gold()
{
cout<<"Mother gold";
}
};
class Child : public Father, public Mother
{
};
int main()
{
Child c;
c.house();
c.gold();
return 0;
}
Output
Father house
Mother gold
3. Multilevel Inheritance in C++
When inheritance happens in multiple levels, it is called multilevel inheritance.
Example:
Grandfather → Father → Son
class Grandfather
{
};
class Father : public Grandfather
{
};
class Son : public Father
{
};
4. Hierarchical Inheritance
When multiple classes inherit from a single base class, it is called hierarchical
inheritance.
Example:
Animal
/ \
Dog Cat
class Animal
{
public:
void eat()
{
cout<<"Eating";
}
};
class Dog : public Animal
{
};
class Cat : public Animal
{
};
5. Hybrid Inheritance
Hybrid inheritance is a combination of multiple inheritance types.
It is generally used in complex software designs.
Access Modes in Inheritance
While inheriting a class, we can use three access modes:
Access Mode
Effect
public
Public members remain public
protected
Members become protected
private
Members become private
Public Inheritance Example
class Parent
{
public:
int value;
};
class Child : public Parent
{
};
int main()
{
Child c;
c.value=10;
}
Advantages of Inheritance
- Improves code reusability
- Supports code extension
- Reduces development time
- Makes programs easier to understand
- Supports polymorphism
Disadvantages of Inheritance
- Creates dependency between classes
- Overuse can make code complicated
- Changes in parent class may affect child classes
Inheritance Interview Questions
1. What is inheritance?
Inheritance allows one class to acquire properties of another class.
2. Which symbol is used for inheritance?
Colon (:) symbol is used.
3. Does C++ support multiple inheritance?
Yes, C++ supports multiple inheritance.
4. Which inheritance improves code reusability?
All types of inheritance improve code reusability.
5. What is the parent class called?
Base class.
Chapter 8 Summary
- Inheritance allows code reuse between classes.
- Base class provides properties.
- Derived class receives properties.
- C++ supports five types of inheritance.
- Inheritance is a major OOP feature.
Next Chapter
In the next chapter, we will learn:
Polymorphism in C++ - Compile Time and Run Time Polymorphism,
Function Overloading, Operator Overloading, and Virtual Functions
Chapter 9: Polymorphism in C++ - Types, Examples and Virtual Functions
Polymorphism is one of the most powerful concepts in Object Oriented Programming (OOP) in C++. The word polymorphism comes from two words: "Poly" meaning many and "Morph" meaning forms.
In simple words, polymorphism means one name having multiple forms or behaviours.
Polymorphism in C++, types of polymorphism in C++, compile time polymorphism, runtime polymorphism, function overloading, operator overloading, virtual functions in C++.
What is Polymorphism in C++?
Polymorphism allows the same function or operator to perform different tasks depending on the situation.
For example, the same word "sound" can have different meanings:
- Dog sound → Bark
- Cat sound → Meow
- Cow sound → Moo
The function name is the same, but behaviour changes. This is called polymorphism.
Types of Polymorphism in C++
C++ mainly supports two types of polymorphism:
1. Compile Time Polymorphism
The decision is made during compilation.
Examples:
Function Overloading
Operator Overloading
2. Runtime Polymorphism
The decision is made during program execution.
Example:
Function Overriding using Virtual Functions
Compile Time Polymorphism
Compile time polymorphism is also called static polymorphism. The compiler decides which function should execute.
1. Function Overloading in C++
Function overloading means creating multiple functions with the same name but different parameters.
The compiler identifies the correct function based on arguments.
Example of Function Overloading:
#include <iostream>
using namespace std;
class Calculator
{
public:
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}
};
int main()
{
Calculator c;
cout<<c.add(10,20)<<endl;
cout<<c.add(10,20,30);
return 0;
}
Output
30 60
Here, the function name is the same but the number of parameters is different.
Rules of Function Overloading
- Function name must be the same.
- Parameters must be different.
- Return type alone cannot overload a function.
- It improves code readability.
2. Operator Overloading in C++
Operator overloading allows operators like +, -, *, etc. to work with user-defined objects.
For example, adding two objects using the + operator.
Example:
#include <iostream>
using namespace std;
class Number
{
public:
int value;
Number(int x)
{
value=x;
}
Number operator +(Number obj)
{
return Number(value + obj.value);
}
};
int main()
{
Number n1(10);
Number n2(20);
Number result=n1+n2;
cout<<result.value;
return 0;
}
Output
30
Runtime Polymorphism in C++
Runtime polymorphism is also called dynamic polymorphism. The function call is decided during execution.
Runtime polymorphism is achieved using:
- Function Overriding
- Virtual Functions
Function Overriding in C++
When a derived class provides its own implementation of a function already defined in the base class, it is called function overriding.
Example:
#include <iostream>
using namespace std;
class Animal
{
public:
void sound()
{
cout<<"Animal sound";
}
};
class Dog : public Animal
{
public:
void sound()
{
cout<<"Dog barks";
}
};
int main()
{
Dog d;
d.sound();
return 0;
}
Output
Dog barks
Virtual Functions in C++
A virtual function is a function in the base class that can be overridden by derived classes.
The virtual keyword is used to achieve runtime polymorphism.
Example of Virtual Function:
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void sound()
{
cout<<"Animal sound";
}
};
class Dog : public Animal
{
public:
void sound()
{
cout<<"Dog barks";
}
};
int main()
{
Animal *a;
Dog d;
a=&d;
a->sound();
return 0;
}
Output
Dog barks
Without the virtual keyword, the base class function would execute.
Pure Virtual Function and Abstract Class
A pure virtual function is a function that has no implementation in the base class.
Syntax:
virtual void functionName() = 0;
A class containing at least one pure virtual function is called an abstract class.
Example:
class Shape
{
public:
virtual void draw()=0;
};
Difference Between Compile Time and Runtime Polymorphism
| Compile Time Polymorphism | Runtime Polymorphism |
|---|---|
| Decision during compilation | Decision during execution |
| Faster execution | Slightly slower |
| Function overloading | Function overriding |
| No virtual keyword | Uses virtual keyword |
Advantages of Polymorphism
- Improves code flexibility
- Reduces complexity
- Supports code reusability
- Makes programs easier to extend
- Helps achieve abstraction
Polymorphism Interview Questions
1. What is polymorphism?
Polymorphism means one name having multiple behaviours.
2. How many types of polymorphism are there?
Compile time and runtime polymorphism.
3. Which keyword is used for runtime polymorphism?
virtual keyword.
4. Can constructors be virtual?
No, constructors cannot be virtual.
5. What is function overloading?
Multiple functions having the same name with different parameters.
Chapter 9 Summary
- Polymorphism means multiple forms.
- C++ supports compile-time and runtime polymorphism.
- Function overloading is compile-time polymorphism.
- Virtual functions provide runtime polymorphism.
- Polymorphism is an important OOP interview topic.
Next Chapter
In the next chapter, we will learn: Encapsulation and Abstraction in C++ with Real-World Examples
Chapter 10: Encapsulation and Abstraction in C++ - Complete Guide
Encapsulation and abstraction are two major pillars of Object Oriented Programming (OOP) in C++. These concepts help developers create secure, reusable, and well-structured programs.
In real-world software development, protecting data and hiding unnecessary implementation details are very important. C++ provides encapsulation and abstraction to achieve these goals.
Encapsulation in C++, abstraction in C++, data hiding in C++, OOP concepts in C++, access modifiers, abstract class in C++, learn C++ programming.
What is Encapsulation in C++?
Encapsulation is the process of wrapping data members and member functions into a single unit called a class.
It also provides data security by controlling access to class members using access specifiers.
Real-World Example
Think about an ATM machine.
- You can withdraw money using buttons.
- You cannot directly access the internal banking system.
- The internal process is hidden from users.
This concept is similar to encapsulation.
How Encapsulation Works in C++?
Encapsulation is achieved using:
- Classes
- Private data members
- Public member functions
Example of Encapsulation in C++
#include <iostream>
using namespace std;
class BankAccount
{
private:
int balance;
public:
void setBalance(int amount)
{
balance = amount;
}
int getBalance()
{
return balance;
}
};
int main()
{
BankAccount account;
account.setBalance(5000);
cout<<account.getBalance();
return 0;
}
Output
5000
Explanation of Above Program
- The balance variable is private, so it cannot be accessed directly.
- The setBalance() function modifies the value.
- The getBalance() function reads the value.
- This protects data from unauthorized access.
Advantages of Encapsulation
Data Security
Private members prevent unwanted access.
Better Control
Programmers can control how data is modified.
Code Maintenance
Changes can be made easily without affecting other parts.
Code Reusability
Classes can be reused in multiple programs.
Access Specifiers Used in Encapsulation
| Access Specifier | Description |
|---|---|
| public | Accessible from anywhere in the program. |
| private | Accessible only inside the class. |
| protected | Accessible inside class and derived classes. |
What is Abstraction in C++?
Abstraction means hiding internal implementation details and showing only essential information to the user.
It focuses on what an object does rather than how it does it.
Real-World Example
When you drive a car:
- You use steering, brake, and accelerator.
- You don't need to know how the engine internally works.
This is abstraction.
How to Achieve Abstraction in C++?
C++ provides abstraction using:
- Classes
- Access specifiers
- Abstract classes
- Pure virtual functions
Example of Abstraction Using Class
#include <iostream>
using namespace std;
class Car
{
private:
void engineStart()
{
cout<<"Engine Started";
}
public:
void start()
{
engineStart();
}
};
int main()
{
Car c;
c.start();
return 0;
}
Output
Engine Started
The user only calls start(). The internal engineStart() implementation remains hidden.
Abstract Class in C++
A class that contains at least one pure virtual function is called an abstract class.
Objects cannot be created directly from an abstract class.
Syntax:
class Shape
{
public:
virtual void draw() = 0;
};
Example of Abstract Class
#include <iostream>
using namespace std;
class Shape
{
public:
virtual void area() = 0;
};
class Circle : public Shape
{
public:
void area()
{
cout<<"Area of Circle";
}
};
int main()
{
Circle c;
c.area();
return 0;
}
Output
Area of Circle
Difference Between Encapsulation and Abstraction
| Encapsulation | Abstraction |
|---|---|
| Wrapping data and functions together | Hiding implementation details |
| Focuses on data security | Focuses on simplicity |
| Achieved using classes and access modifiers | Achieved using abstract classes and interfaces |
| Example: Private variables | Example: Virtual functions |
Encapsulation vs Abstraction - Simple Understanding
Encapsulation: How to protect data?
Abstraction: How to hide unnecessary details?
Common Interview Questions
1. What is encapsulation?
Combining data and functions into a single unit is encapsulation.
2. Why do we use private variables?
To protect data from direct access.
3. What is abstraction?
Hiding implementation details and showing only important features.
4. Can we create objects of abstract classes?
No, abstract classes cannot create objects directly.
5. Which keyword is used for pure virtual functions?
The virtual keyword with =0 syntax.
Chapter 10 Summary
- Encapsulation combines data and functions.
- Private members provide data security.
- Abstraction hides complex implementation.
- Abstract classes contain pure virtual functions.
- Both concepts improve software design.
Next Chapter
In the next chapter, we will learn: Friend Functions and Friend Classes in C++ with Examples
Chapter 11: Friend Function and Friend Class in C++ - Complete Guide
In the previous chapter, we learned about encapsulation and abstraction in C++. Encapsulation protects data by restricting direct access to class members.
However, sometimes we need to allow a specific external function or another class to access private and protected members.
For this purpose, C++ provides a special feature called Friend Function and Friend Class.
Friend function in C++, friend class in C++, private member access, C++ OOP concepts, learn advanced C++ programming, C++ interview questions.
What is a Friend Function in C++?
A friend function is a function that is not a member of a class but can access private and protected members of that class.
A friend function is declared inside the class using the keyword friend.
Syntax of Friend Function
class ClassName
{
private:
int value;
public:
friend void functionName();
};
Important Properties of Friend Function
- Friend functions are not class members.
- They can access private and protected data.
- They are declared using the friend keyword.
- They are called like normal functions.
- They do not use the this pointer.
Example of Friend Function in C++
#include <iostream>
using namespace std;
class Number
{
private:
int value;
public:
Number()
{
value = 100;
}
friend void display(Number n);
};
void display(Number n)
{
cout<<"Value is: "<
Output
Value is: 100
Explanation of Program
-
The variable value is private.
-
Normally, outside functions cannot access private members.
-
The display() function is declared as a friend.
-
Because of friendship, it can access value directly.
Friend Function With Multiple Classes
A single friend function can access private members of multiple classes.
Example:
#include <iostream>
using namespace std;
class B;
class A
{
int x;
public:
A()
{
x=10;
}
friend void add(A,B);
};
class B
{
int y;
public:
B()
{
y=20;
}
friend void add(A,B);
};
void add(A a,B b)
{
cout<<"Sum = "<
Output
Sum = 30
Advantages of Friend Function
Access Private Data
Allows controlled access to private members.
Improves Flexibility
Useful when external functions need special access.
Useful in Operator Overloading
Many operator overloads use friend functions.
Code Sharing
Allows communication between classes.
What is a Friend Class in C++?
A friend class is a class that can access private and protected members of
another class.
When one class is declared as a friend of another class, all member functions
of the friend class can access private data.
Syntax of Friend Class
class A
{
friend class B;
};
class B
{
};
Example of Friend Class in C++
#include <iostream>
using namespace std;
class Student
{
private:
int marks;
public:
Student()
{
marks=95;
}
friend class Result;
};
class Result
{
public:
void show(Student s)
{
cout<<"Marks: "<
Output
Marks: 95
Friend Function vs Friend Class
Friend Function
Friend Class
A single function gets access.
Complete class gets access.
Declared using friend function.
Declared using friend class.
Used for specific operations.
Used when many functions require access.
Less access.
More access.
Friendship Rules in C++
-
Friendship is not inherited.
-
Friendship is not mutual automatically.
-
Friend functions are not called using objects.
-
Friend functions can access private and protected members.
-
Friendship should be used carefully because it reduces data hiding.
Real-World Example of Friend Function
Consider a bank application.
Normally, account details are private.
But an authorized auditing function may need access to verify information.
That auditing function can be implemented as a friend function.
Common Interview Questions on Friend Function
1. What is a friend function in C++?
A non-member function that can access private and protected members.
2. Which keyword is used to create friendship?
The friend keyword.
3. Is friend function a member function?
No, it is an external function.
4. Can friend function access private variables?
Yes, if declared as a friend.
5. Is friendship inherited?
No, friendship is not inherited.
Chapter 11 Summary
-
Friend functions provide controlled access to private members.
-
Friend classes allow complete class access.
-
Friendship improves flexibility but should be used carefully.
-
Friend features are commonly used in operator overloading.
Next Chapter
In the next chapter, we will learn:
Constructor and Destructor in C++ with Real-Time Examples
Chapter 12: Constructors and Destructors in C++ - Complete Guide
In the previous chapter, we learned about friend functions and friend classes. Now we will learn one of the most important concepts in C++: Constructors and Destructors.
Constructors and destructors are special member functions that are automatically called during the lifetime of an object.
Constructor in C++, destructor in C++, default constructor, parameterized constructor, copy constructor, object initialization, C++ object lifecycle, C++ OOP concepts.
What is a Constructor in C++?
A constructor is a special member function of a class that is automatically executed when an object is created.
The main purpose of a constructor is to initialize object data members.
Features of Constructor
- Constructor name must be the same as the class name.
- Constructor does not have a return type.
- It is automatically called when an object is created.
- A class can have multiple constructors.
- Constructors can be overloaded.
Basic Syntax of Constructor
class ClassName
{
public:
ClassName()
{
// constructor body
}
};
Example of Simple Constructor
#include <iostream>
using namespace std;
class Student
{
public:
Student()
{
cout<<"Constructor Called";
}
};
int main()
{
Student s;
return 0;
}
Output
Constructor Called
Types of Constructors in C++
C++ mainly supports three types of constructors:
1. Default Constructor
Constructor without parameters.
2. Parameterized Constructor
Constructor with parameters.
3. Copy Constructor
Creates a new object from an existing object.
1. Default Constructor in C++
A constructor that does not accept any arguments is called a default constructor.
Example:
#include <iostream>
using namespace std;
class Car
{
public:
Car()
{
cout<<"Car object created";
}
};
int main()
{
Car c;
return 0;
}
Output
Car object created
2. Parameterized Constructor in C++
A constructor that accepts arguments is called a parameterized constructor.
It is used to initialize objects with different values.
Example:
#include <iostream>
using namespace std;
class Employee
{
int id;
public:
Employee(int x)
{
id=x;
}
void display()
{
cout<<"Employee ID: "<
Output
Employee ID: 101
3. Copy Constructor in C++
A copy constructor initializes one object using another object of the same class.
Syntax:
ClassName(const ClassName &object)
{
}
Example:
#include <iostream>
using namespace std;
class Number
{
int value;
public:
Number(int x)
{
value=x;
}
Number(Number &obj)
{
value=obj.value;
}
void show()
{
cout<
Output
50
Constructor Overloading in C++
Creating multiple constructors with different parameters in the same class is
called constructor overloading.
Example:
class Rectangle
{
public:
Rectangle()
{
cout<<"No values";
}
Rectangle(int length)
{
cout<<"Length: "<
What is Destructor in C++?
A destructor is a special member function that is automatically called when an
object is destroyed.
It is mainly used to release memory and resources.
Destructor Syntax:
~ClassName()
{
// destructor body
}
Features of Destructor
-
Destructor name is the class name with a tilde (~) symbol.
-
Destructor has no return type.
-
Destructor cannot have parameters.
-
Only one destructor can exist in a class.
-
It executes automatically when object lifetime ends.
Example of Destructor in C++
#include <iostream>
using namespace std;
class Demo
{
public:
Demo()
{
cout<<"Constructor Executed"<
Output
Constructor Executed
Destructor Executed
Constructor vs Destructor
Constructor
Destructor
Used to initialize objects.
Used to destroy objects.
Called when object is created.
Called when object is removed.
Can have parameters.
Cannot have parameters.
Multiple constructors are possible.
Only one destructor is possible.
Name is same as class name.
Name starts with ~ symbol.
Constructor and Destructor Execution Order
When multiple objects are created:
-
Constructor executes in object creation order.
-
Destructor executes in reverse order.
Real-Time Example
Bank Application
When an account object is created:
-
Constructor initializes account details.
-
Destructor closes resources after the account object is removed.
Common Interview Questions
1. Why constructor has no return type?
Because it is automatically managed by the compiler.
2. Can constructor be private?
Yes, private constructors are used in singleton design patterns.
3. Can destructor be overloaded?
No, only one destructor is allowed.
4. When is destructor called?
When the object goes out of scope or is deleted.
5. What is the difference between constructor and normal function?
Constructor initializes objects automatically, while normal functions are called manually.
Chapter 12 Summary
-
Constructors initialize objects automatically.
-
Destructors clean resources automatically.
-
C++ supports default, parameterized, and copy constructors.
-
Constructor overloading allows multiple initialization methods.
-
Destructor helps in memory management.
Next Chapter
Next chapter:
Inheritance in C++ - Types, Syntax, Examples and Real-World Usage
Chapter 13: Inheritance in C++ - Types, Syntax, Examples and Real-World Usage
In the previous chapter, we learned about constructors and destructors in C++. Now we are going to learn another important Object Oriented Programming concept: Inheritance.
Inheritance is one of the most powerful features of C++ that allows a new class to reuse the properties and behaviors of an existing class.
Inheritance in C++, types of inheritance in C++, single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance, hybrid inheritance, OOP concepts in C++, C++ tutorial.
What is Inheritance in C++?
Inheritance is a mechanism where one class acquires the properties and functions of another class.
The existing class is called the:
- Base Class
- Parent Class
- Super Class
The new class is called the:
- Derived Class
- Child Class
Real-World Example of Inheritance
Consider a vehicle system.
- Vehicle is a general class.
- Car and Bike can inherit common vehicle features.
- They can also have their own additional features.
This reduces duplicate code and improves reusability.
Syntax of Inheritance in C++
class DerivedClass : access_mode BaseClass
{
// derived class members
};
Access mode can be:
- public
- private
- protected
Example of Simple Inheritance
#include <iostream>
using namespace std;
class Animal
{
public:
void eat()
{
cout<<"Eating food"<
Output
Eating food
Dog is barking
Advantages of Inheritance
Code Reusability
Existing code can be reused instead of writing again.
Easy Maintenance
Changes in parent class automatically affect child classes.
Better Organization
Classes can be arranged in a logical structure.
Supports Polymorphism
Inheritance helps achieve runtime polymorphism.
Types of Inheritance in C++
C++ supports five major types of inheritance:
- Single Inheritance
- Multiple Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
1. Single Inheritance
When one derived class inherits from one base class, it is called single
inheritance.
Structure:
Animal
|
|
Dog
Example:
class Animal
{
public:
void eat()
{
cout<<"Eating";
}
};
class Dog : public Animal
{
};
2. Multiple Inheritance
When one derived class inherits from more than one base class, it is called
multiple inheritance.
Structure:
Class A Class B
\ /
Class C
Example:
#include <iostream>
using namespace std;
class Father
{
public:
void showFather()
{
cout<<"Father";
}
};
class Mother
{
public:
void showMother()
{
cout<<"Mother";
}
};
class Child : public Father, public Mother
{
};
int main()
{
Child c;
c.showFather();
c.showMother();
return 0;
}
Output
Father
Mother
3. Multilevel Inheritance
When a derived class becomes the base class for another class, it is called
multilevel inheritance.
Structure:
Grandfather
|
Father
|
Son
Example:
class Grandfather
{
public:
void property()
{
cout<<"Property";
}
};
class Father : public Grandfather
{
};
class Son : public Father
{
};
4. Hierarchical Inheritance
When multiple derived classes inherit from a single base class, it is called
hierarchical inheritance.
Structure:
Vehicle
/ \
Car Bike
Example:
class Vehicle
{
public:
void start()
{
cout<<"Vehicle Started";
}
};
class Car : public Vehicle
{
};
class Bike : public Vehicle
{
};
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance.
It is commonly created by combining multiple and multilevel inheritance.
Diamond Problem
Hybrid inheritance can create ambiguity when two classes inherit the same
base class.
C++ solves this problem using virtual inheritance.
Access Modes in Inheritance
Inheritance Mode
Public Members
Protected Members
Private Members
Public
Public
Protected
Not Accessible
Protected
Protected
Protected
Not Accessible
Private
Private
Private
Not Accessible
Inheritance and Constructors
When inheritance is used, the base class constructor executes first, followed
by the derived class constructor.
Base Constructor
↓
Derived Constructor
Inheritance and Destructors
Destructor execution happens in reverse order.
Derived Destructor
↓
Base Destructor
Common Interview Questions
1. What is inheritance in C++?
Inheritance allows one class to acquire properties of another class.
2. Why do we use inheritance?
To achieve code reusability and reduce duplication.
3. What are the types of inheritance?
Single, multiple, multilevel, hierarchical, and hybrid.
4. Can private members be inherited?
They exist in the object but cannot be directly accessed by derived classes.
5. What is the diamond problem?
Ambiguity caused by multiple inheritance.
Chapter 13 Summary
-
Inheritance allows code reuse between classes.
-
Base class provides common functionality.
-
Derived class adds new features.
-
C++ supports five types of inheritance.
-
Virtual inheritance solves diamond problems.
Next Chapter
Next chapter:
Polymorphism in C++ - Compile Time and Runtime Polymorphism with Examples
Chapter 14: Polymorphism in C++ - Types, Examples, Virtual Functions and Programs
In the previous chapter, we learned about inheritance in C++. Now we will learn another important Object Oriented Programming concept called Polymorphism.
Polymorphism is one of the four major pillars of OOP along with encapsulation, abstraction, and inheritance.
Polymorphism in C++, compile time polymorphism, runtime polymorphism, function overloading, operator overloading, function overriding, virtual function in C++, OOP concepts in C++.
What is Polymorphism in C++?
The word polymorphism is derived from two words:
- Poly - Many
- Morph - Forms
Polymorphism means "one name having multiple forms".
In C++, the same function or operator can perform different tasks depending on the situation.
Real-World Example of Polymorphism
A person can have different roles:
- A person can be a student.
- The same person can be an employee.
- The same person can be a customer.
The same entity behaves differently in different situations. This is polymorphism.
Types of Polymorphism in C++
C++ mainly supports two types of polymorphism:
1. Compile Time Polymorphism
Decision is made during compilation.
2. Runtime Polymorphism
Decision is made during program execution.
1. Compile Time Polymorphism in C++
Compile time polymorphism is also called static polymorphism.
The compiler decides which function should execute before the program runs.
It is achieved using:
- Function Overloading
- Operator Overloading
Function Overloading in C++
Function overloading allows multiple functions with the same name but different parameters.
Rules of Function Overloading
- Functions must have different number of arguments or different data types.
- Return type alone cannot overload a function.
Example of Function Overloading
#include <iostream>
using namespace std;
class Calculator
{
public:
int add(int a,int b)
{
return a+b;
}
float add(float a,float b)
{
return a+b;
}
};
int main()
{
Calculator c;
cout<
Output
30
8
Operator Overloading in C++
Operator overloading allows operators like +, -, *, etc. to work with user
defined objects.
It gives special meaning to existing operators.
Example of Operator Overloading
#include <iostream>
using namespace std;
class Number
{
int value;
public:
Number(int x)
{
value=x;
}
Number operator +(Number obj)
{
return Number(value+obj.value);
}
void display()
{
cout<
Output
30
2. Runtime Polymorphism in C++
Runtime polymorphism is also called
dynamic polymorphism.
The decision about which function to call happens during execution.
Runtime polymorphism is achieved using:
-
Function overriding
-
Virtual functions
Function Overriding in C++
When a derived class provides its own implementation of a base class function,
it is called function overriding.
Example of Function Overriding
#include <iostream>
using namespace std;
class Animal
{
public:
void sound()
{
cout<<"Animal sound";
}
};
class Dog : public Animal
{
public:
void sound()
{
cout<<"Dog barking";
}
};
int main()
{
Dog d;
d.sound();
return 0;
}
Output
Dog barking
Virtual Function in C++
A virtual function is a function declared in the base class using the
virtual keyword.
It allows the derived class function to execute through a base class pointer.
Syntax:
class Base
{
public:
virtual void show();
};
Example of Virtual Function
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void sound()
{
cout<<"Animal sound";
}
};
class Dog : public Animal
{
public:
void sound()
{
cout<<"Dog barking";
}
};
int main()
{
Animal *a;
Dog d;
a=&d;
a->sound();
return 0;
}
Output
Dog barking
Why Do We Need Virtual Functions?
-
They provide dynamic method selection.
-
They support runtime polymorphism.
-
They improve flexibility of large applications.
-
They allow base pointers to call derived implementations.
Pure Virtual Function in C++
A virtual function without implementation is called a pure virtual function.
Syntax:
virtual void display() = 0;
A class containing a pure virtual function becomes an abstract class.
Difference Between Compile Time and Runtime Polymorphism
Compile Time Polymorphism
Runtime Polymorphism
Decision made during compilation.
Decision made during execution.
Faster execution.
Slightly slower due to dynamic binding.
Uses overloading.
Uses overriding.
Example: Function overloading.
Example: Virtual functions.
Static Binding vs Dynamic Binding
Static Binding:
Function call is connected during compilation.
Dynamic Binding:
Function call is decided during runtime.
Common Interview Questions
1. What is polymorphism?
Ability of one object or function to behave in multiple forms.
2. What are the types of polymorphism?
Compile time and runtime polymorphism.
3. What is function overloading?
Creating multiple functions with the same name but different parameters.
4. What is function overriding?
Redefining a base class function in derived class.
5. Why do we use virtual functions?
To achieve runtime polymorphism.
Chapter 14 Summary
-
Polymorphism means many forms.
-
Compile time polymorphism uses overloading.
-
Runtime polymorphism uses overriding and virtual functions.
-
Virtual functions enable dynamic binding.
-
Polymorphism improves flexibility and scalability.
Next Chapter
Next chapter:
Exception Handling in C++ - try, catch, throw, Custom Exceptions and Best Practices
Exception Handling in C++ Programming Language
Exception handling is one of the most important concepts in C++ programming. It is used to handle runtime errors gracefully without stopping the normal execution of a program.
While writing programs, unexpected situations may occur such as division by zero, invalid input, file opening failure, or memory allocation problems. C++ provides an exception handling mechanism using three important keywords: try, throw, and catch.
What You Will Learn in This Chapter
- What is an exception?
- Why exception handling is required
- try block
- throw keyword
- catch block
- Multiple catch blocks
- Nested exception handling
- Custom exceptions
- Standard exceptions in C++
- Best practices
What is an Exception in C++?
An exception is an abnormal condition that occurs during program execution and changes the normal flow of the program.
Examples of exceptions:
- Division by zero
- Array index out of range
- File not found
- Invalid user input
- Memory allocation failure
Example Without Exception Handling
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 0;
cout << a / b;
return 0;
}
The above program may terminate abnormally because division by zero is not allowed.
Why Do We Need Exception Handling?
- Prevents sudden program termination.
- Separates error handling code from normal program logic.
- Makes programs more reliable and easier to debug.
- Improves user experience.
- Helps handle unexpected runtime situations.
Exception Handling Keywords in C++
| Keyword | Purpose |
|---|---|
| try | Contains code that may generate an exception. |
| throw | Used to generate an exception. |
| catch | Handles the exception thrown by try block. |
Basic Syntax of Exception Handling
try
{
// risky code
throw exception;
}
catch(type variable)
{
// handling code
}
Simple Exception Handling Example
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 0;
try
{
if(b == 0)
{
throw "Division by zero is not possible";
}
cout << a/b;
}
catch(const char* message)
{
cout << message;
}
return 0;
}
Output:
How Exception Handling Works?
1. Program enters the try block.
2. If an error occurs, throw sends the exception.
3. Control moves to the matching catch block.
4. The error is handled and program continues execution.
Multiple Catch Blocks
A program can have multiple catch blocks to handle different types of exceptions.
#include <iostream>
using namespace std;
int main()
{
try
{
throw 100;
}
catch(int x)
{
cout<<"Integer exception: "<
Output:
Integer exception: 100
Catch All Exceptions
Sometimes we may not know the type of exception.
In such situations, we can use the catch-all handler.
try
{
throw 5.5;
}
catch(...)
{
cout<<"Exception occurred";
}
Nested Exception Handling
A try block can contain another try block. This is called nested exception handling.
try
{
try
{
throw 10;
}
catch(int x)
{
cout<<"Inner Exception";
}
}
catch(...)
{
cout<<"Outer Exception";
}
Throwing Exceptions From Functions
Exceptions can also be generated inside functions and handled in another location.
#include<iostream>
using namespace std;
void checkAge(int age)
{
if(age < 18)
{
throw age;
}
}
int main()
{
try
{
checkAge(15);
}
catch(int age)
{
cout<<"Age is not allowed";
}
return 0;
}
Standard Exceptions in C++
C++ provides many built-in exception classes through the
<exception> and related header files.
Exception
Meaning
exception
Base class for exceptions
runtime_error
Runtime related errors
logic_error
Logical errors
bad_alloc
Memory allocation failure
out_of_range
Invalid index access
Using Standard Exception Example
#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
try
{
throw runtime_error("Runtime error occurred");
}
catch(exception &e)
{
cout<<e.what();
}
return 0;
}
Output:
Runtime error occurred
Custom Exception Classes
C++ allows programmers to create their own exception classes by inheriting from
the standard exception class.
#include<iostream>
using namespace std;
class MyException
{
};
int main()
{
try
{
throw MyException();
}
catch(MyException)
{
cout<<"Custom Exception";
}
return 0;
}
Exception Handling Best Practices
- Always handle exceptions that can occur.
- Do not use exceptions for normal program flow.
- Catch specific exceptions before general exceptions.
- Use meaningful error messages.
- Do not hide exceptions without proper handling.
- Release resources properly after exceptions.
Exception Handling Interview Questions
1. What is exception handling in C++?
It is a mechanism used to handle runtime errors using try, throw and catch.
2. Difference between error and exception?
Errors are serious problems that may stop execution, while exceptions are
conditions that can often be handled during runtime.
3. Can we use multiple catch blocks?
Yes, multiple catch blocks can handle different exception types.
4. What happens if an exception is not caught?
The program calls terminate() and stops execution.
Next Chapter:
File Handling in C++ Programming
Reading, writing, opening, closing files and file streams with examples.
File Handling in C++ Programming Language
File handling is an important concept in C++ that allows programs to store data permanently in files. Normally, variables store data temporarily in RAM, but file handling allows us to save information permanently on a storage device.
In real-world applications, file handling is used for storing user details, database information, reports, configuration files, logs, and much more.
What You Will Learn in This Chapter
- What is file handling?
- File streams in C++
- Opening and closing files
- Writing data into files
- Reading data from files
- File modes
- Appending data
- Binary files
- File handling interview questions
What is File Handling?
File handling is the process of creating, opening, reading, writing, and managing files using programming languages.
C++ provides file handling through the <fstream> header file.
Include File Handling Library
#include <fstream>
File Streams in C++
C++ uses streams to communicate between the program and files.
| Class | Purpose |
|---|---|
| ofstream | Used for writing data into files. |
| ifstream | Used for reading data from files. |
| fstream | Used for both reading and writing. |
Creating and Opening a File
To create or open a file, we use the file stream objects.
Example: Creating a File
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("student.txt");
file<<"Welcome to C++ File Handling";
file.close();
return 0;
}
Output:
Writing Data Into a File
The ofstream class is used to write information into files.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream myFile("data.txt");
myFile<<"Learning C++ Programming";
myFile.close();
return 0;
}
The text will be stored inside data.txt.
Reading Data From a File
The ifstream class is used to read data from files.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
string data;
ifstream myFile("data.txt");
while(getline(myFile,data))
{
cout<
Output:
Learning C++ Programming
Checking Whether File Opened Successfully
It is a good programming practice to check whether a file exists before reading or
writing.
#include
#include
using namespace std;
int main()
{
ifstream file("sample.txt");
if(file.is_open())
{
cout<<"File opened successfully";
}
else
{
cout<<"Unable to open file";
}
return 0;
}
Closing a File
After completing file operations, we should close the file using the close()
function.
file.close();
Closing files releases system resources and prevents data corruption.
File Opening Modes in C++
Mode
Purpose
ios::in
Open file for reading
ios::out
Open file for writing
ios::app
Add data at the end of file
ios::ate
Move pointer to end of file
ios::binary
Open binary file
ios::trunc
Delete existing file contents
Appending Data to a File
Appending means adding new data without deleting existing content.
#include
#include
using namespace std;
int main()
{
ofstream file;
file.open("data.txt",ios::app);
file<<"New Line Added";
file.close();
return 0;
}
File Pointers in C++
C++ maintains two important file pointers:
Pointer
Purpose
get pointer
Used for reading data
put pointer
Used for writing data
Binary File Handling
Binary files store data in binary format instead of normal text format.
They are faster and useful for storing objects and large amounts of data.
Writing Binary Data
file.write((char*)&object,sizeof(object));
Reading Binary Data
file.read((char*)&object,sizeof(object));
Important File Handling Functions
Function
Purpose
open()
Opens a file
close()
Closes a file
getline()
Reads complete line
read()
Reads binary data
write()
Writes binary data
eof()
Checks end of file
Advantages of File Handling
- Permanent data storage
- Easy data retrieval
- Handles large amounts of information
- Useful for real-world applications
- Improves program flexibility
File Handling Interview Questions
1. Which header file is used for file handling in C++?
The <fstream> header file is used.
2. Difference between ifstream and ofstream?
ifstream reads data from files, while ofstream writes data into files.
3. Why should we close a file?
Closing a file releases resources and ensures data is properly saved.
4. What is the difference between text and binary files?
Text files store readable characters, while binary files store data in binary format.
Next Chapter:
Templates in C++ Programming
Function templates, class templates, generic programming and examples.
Templates in C++ Programming Language
Templates are one of the most powerful features of C++ that allow programmers to write reusable and flexible code. Using templates, we can create a single function or class that works with different data types.
Before templates, programmers had to write separate functions for different data types like int, float, double, etc. Templates solve this problem by supporting generic programming.
Topics Covered in This Chapter
- What are templates in C++?
- Advantages of templates
- Function templates
- Class templates
- Multiple template parameters
- Template specialization
- Real-world usage
- Template interview questions
What are Templates in C++?
A template is a feature in C++ that allows us to create generic programs. The compiler automatically generates the required code based on the data type provided.
Simple Example Without Template
#include<iostream>
using namespace std;
int addInt(int a,int b)
{
return a+b;
}
float addFloat(float a,float b)
{
return a+b;
}
int main()
{
cout<
In the above example, we created two functions for two different data types.
Templates remove this repeated code.
Advantages of Templates
- Code reusability
- Reduces duplicate code
- Improves program efficiency
- Supports generic programming
- Provides type safety
Types of Templates in C++
Type
Description
Function Template
Used to create generic functions
Class Template
Used to create generic classes
# Function Templates
Function Template in C++
A function template allows a function to work with different data types without
writing separate functions.
Syntax:
template <typename T>
return_type function_name(T parameter)
{
//function body
}
Example: Function Template
#include<iostream>
using namespace std;
template <typename T>
T addition(T a,T b)
{
return a+b;
}
int main()
{
cout<
Output:
30
8
The same function works for both integer and floating-point values.
Template Keyword in C++
The keyword template is used to create templates.
The keyword typename represents a generic data type.
Example:
template <typename T>
Here T is not a fixed data type. It can become int, float, double, char, or any
user-defined type.
Class Templates in C++
A class template allows us to create classes that work with different data types.
Syntax:
template <class T>
class ClassName
{
T variable;
};
Example: Class Template
#include<iostream>
using namespace std;
template<class T>
class Data
{
T value;
public:
Data(T v)
{
value=v;
}
void display()
{
cout<<"Value: "<
Output:
Value: 100
Value: 25.5
Multiple Template Parameters
Templates can accept more than one parameter.
Example:
#include
using namespace std;
template<class T,class U>
class Test
{
T first;
U second;
public:
Test(T a,U b)
{
first=a;
second=b;
}
void show()
{
cout<
Output:
10 5.5
Template Specialization
Sometimes we need different behavior for a specific data type.
Template specialization allows us to customize the template implementation.
Example:
template<class T>
class Example
{
public:
void show()
{
cout<<"Generic Template";
}
};
template<>
class Example<int>
{
public:
void show()
{
cout<<"Integer Specialization";
}
};
Templates and STL
The Standard Template Library (STL) in C++ is completely based on templates.
Examples of STL components:
- vector
- list
- stack
- queue
- map
- set
Example:
#include<vector>
using namespace std;
vector<int> numbers;
Here vector is a template class that works with integer data.
Advantages of Generic Programming
- Write once and use many times
- Less maintenance
- Cleaner code
- Better software design
- Supports large applications
Common Mistakes While Using Templates
- Using unsupported operations for a data type
- Making templates unnecessarily complex
- Ignoring compiler error messages
- Creating too many template parameters
C++ Templates Interview Questions
1. What is a template in C++?
A template is a feature that allows writing generic code that works with
multiple data types.
2. What are the types of templates?
Function templates and class templates.
3. Which keyword is used to create templates?
The template keyword is used.
4. What is STL?
STL is the Standard Template Library that provides ready-made template-based
containers and algorithms.
5. Difference between class and function templates?
Function templates create generic functions, while class templates create
generic classes.
Next Chapter:
Standard Template Library (STL) in C++
Vectors, Lists, Maps, Sets, Iterators, Algorithms and Real-Time Examples.
Multithreading in C++ Programming Language
Modern applications need to perform multiple tasks at the same time. For example, a web browser downloads files while allowing users to browse, or a music player plays songs while loading playlists.
Multithreading in C++ allows a program to execute multiple tasks concurrently inside a single process. It improves performance, responsiveness, and resource utilization.
Topics Covered in This Chapter
- What is a thread?
- Process vs Thread
- Advantages of multithreading
- Thread creation in C++
- Passing arguments to threads
- Joining and detaching threads
- Thread synchronization
- Mutex
- Race conditions
- Deadlock
- Thread interview questions
What is a Thread?
A thread is a lightweight unit of execution inside a process. A single program can contain multiple threads running independently.
Each thread shares the same memory space of its parent process but executes its own instructions.
Process vs Thread
| Process | Thread |
|---|---|
| Heavyweight execution unit | Lightweight execution unit |
| Has separate memory | Shares process memory |
| Creation is slower | Creation is faster |
| Communication is difficult | Communication is easier |
What is Multithreading?
Multithreading is a programming technique where multiple threads execute different parts of a program simultaneously.
Example:
- One thread downloads a file
- Another thread updates the user interface
- Another thread processes data
Advantages of Multithreading
- Improves application performance
- Makes programs more responsive
- Better CPU utilization
- Handles multiple tasks efficiently
- Useful in games, servers, and real-time applications
C++ Thread Library
C++11 introduced the standard thread library that provides support for multithreading.
Header File:
#include<thread>
Creating a Thread in C++
A thread can be created using the thread class.
Example: Simple Thread Program
#include<iostream>
#include<thread>
using namespace std;
void display()
{
cout<<"Thread is running";
}
int main()
{
thread t(display);
t.join();
return 0;
}
Output:
Understanding join()
The join() function makes the main thread wait until the created thread finishes execution.
t.join();
Without join(), the program may terminate before the thread completes.
Understanding detach()
detach() allows a thread to execute independently without waiting for completion.
t.detach();
After detaching, the thread runs in the background.
Passing Arguments to Threads
Arguments can be passed while creating a thread.
Example:
#include#include using namespace std; void printNumber(int value) { cout< Output:
100Multiple Threads in C++
#include#include using namespace std; void task1() { cout<<"Task 1"; } void task2() { cout<<"Task 2"; } int main() { thread t1(task1); thread t2(task2); t1.join(); t2.join(); return 0; } Thread Synchronization
When multiple threads access shared data, unexpected results can occur. Synchronization controls the access to shared resources.
Example problems:
- Data corruption
- Race conditions
- Incorrect output
Race Condition in C++
A race condition occurs when multiple threads access and modify shared data at the same time.
Example:
int counter=0; Thread 1: counter++; Thread 2: counter++;The final value may not be correct because both threads modify the same variable simultaneously.
Mutex in C++
Mutex stands for Mutual Exclusion. It prevents multiple threads from accessing shared resources at the same time.
Header File:
#include<mutex>Example:
#include#include #include using namespace std; mutex m; void print() { m.lock(); cout<<"Safe execution"; m.unlock(); } int main() { thread t1(print); thread t2(print); t1.join(); t2.join(); return 0; } lock_guard in C++
lock_guard automatically locks and unlocks a mutex. It is safer than manually calling lock() and unlock().
Example:
lock_guard<mutex> lock(m);Deadlock in Multithreading
Deadlock happens when two or more threads wait forever for each other to release resources.
Example:
- Thread A holds Resource 1 and waits for Resource 2
- Thread B holds Resource 2 and waits for Resource 1
Both threads remain blocked permanently.
How to Avoid Deadlocks
- Lock resources in the same order
- Avoid unnecessary locks
- Use lock_guard and scoped locks
- Keep critical sections small
Thread Lifecycle
Stage Description Created Thread object is created Running Thread executes instructions Waiting Thread waits for resources Finished Thread completes execution Real World Uses of Multithreading
- Operating systems
- Web servers
- Games
- Video processing
- Database systems
- Mobile applications
- Artificial intelligence applications
C++ Multithreading Interview Questions
1. What is a thread?A thread is a lightweight execution unit inside a process.
2. What is multithreading?Multithreading allows multiple threads to execute tasks concurrently.
3. What is mutex?Mutex is a synchronization mechanism used to protect shared resources.
4. Difference between join() and detach()?join() waits for thread completion, while detach() allows independent execution.
5. What is a race condition?A race condition occurs when multiple threads access shared data simultaneously causing unexpected results.
Next Chapter:
Modern C++ Features (C++11, C++14, C++17, C++20)
auto, lambda expressions, smart pointers, move semantics, constexpr, range-based loops and modern coding practices.
Modern C++ Features and Updates
C++ has continuously evolved since its creation. Modern versions of C++ introduced many powerful features that make programming easier, safer, faster, and more efficient.
The major modern versions are: C++11, C++14, C++17, and C++20. These updates changed the way developers write professional C++ applications.
Topics Covered in This Chapter
- Evolution of C++ standards
- auto keyword
- Range-based for loop
- Lambda expressions
- Smart pointers
- Move semantics
- nullptr
- constexpr
- Structured bindings
- Concepts in C++20
- Modern C++ best practices
Evolution of C++ Standards
| Version | Released | Main Features |
|---|---|---|
| C++11 | 2011 | Major language improvement |
| C++14 | 2014 | Improved C++11 features |
| C++17 | 2017 | Better syntax and libraries |
| C++20 | 2020 | Concepts, modules, coroutines |
C++11 Features
1. auto Keyword
The auto keyword allows the compiler to automatically determine the data type of a variable.
Example:
#includeusing namespace std; int main() { auto number = 100; auto price = 25.5; cout< Output:
100
25.5The compiler automatically detects:
- number as int
- price as double
2. nullptr in C++
Before C++11, NULL was used to represent null pointers. C++11 introduced nullptr, which is safer.
Example:
int *ptr = nullptr;nullptr has its own type and avoids pointer-related errors.
3. Range-Based For Loop
Range-based loops provide an easier way to iterate through arrays and containers.
Example:
#includeusing namespace std; int main() { int numbers[]={10,20,30}; for(int x:numbers) { cout< Output:
10 20 304. Lambda Expressions
Lambda expressions allow creating anonymous functions directly inside the code.
Syntax:
[capture](parameters) { function body };Example:
#includeusing namespace std; int main() { auto add=[](int a,int b) { return a+b; }; cout< Output:
305. Smart Pointers
Smart pointers automatically manage dynamically allocated memory and prevent memory leaks.
They are available in the <memory> header file.
Types of Smart Pointers:
Pointer Description unique_ptr Owns one object exclusively shared_ptr Multiple owners can share object weak_ptr Non-owning reference Example: unique_ptr
#include#include using namespace std; int main() { unique_ptr ptr(new int(100)); cout<<*ptr; return 0; } 6. Move Semantics
Move semantics allow transferring resources from one object to another without copying data.
It improves performance, especially when handling large objects.
Move Constructor Example:
ClassName(ClassName&& obj) { //move resources }The symbol && represents an rvalue reference.
C++14 Features
1. Generic Lambda
C++14 allows lambda functions to work with different data types.
auto display=[](auto value) { cout<2. Binary Literals
int number = 0b1010;The value represents binary number 1010.
C++17 Features
1. Structured Bindings
Structured bindings allow extracting values from objects easily.
Example:
pair<int,string> student={1,"John"}; auto[id,name]=student; cout<2. if constexpr
if constexpr allows compile-time condition checking.
if constexpr(condition) { }3. std::optional
optional represents a value that may or may not exist.
Example:optional<int> value;C++20 Features
1. Concepts
Concepts allow defining requirements for template parameters.
Example:
templateconcept Number = is_integral_v ; 2. Modules
Modules provide a modern replacement for header files and improve compilation speed.
3. Coroutines
Coroutines allow functions to pause and resume execution.
They are useful in asynchronous programming.
Modern C++ Best Practices
- Use smart pointers instead of raw pointers
- Prefer auto when type is obvious
- Use constexpr for compile-time calculations
- Use range-based loops
- Avoid unnecessary copying
- Use STL containers instead of manually created data structures
- Write clean and readable code
Modern C++ Interview Questions
1. What is auto keyword?auto allows the compiler to automatically determine variable data types.
2. Why was nullptr introduced?nullptr provides safer null pointer handling compared to NULL.
3. What are smart pointers?Smart pointers automatically manage dynamically allocated memory.
4. What is a lambda expression?A lambda is an anonymous function that can be created inline.
5. What is move semantics?Move semantics transfers resources instead of copying them, improving performance.
Next Chapter:
Advanced C++ Memory Management
Stack, Heap, Memory Allocation, Smart Memory Handling, Memory Leaks, Dangling Pointers and Optimization Techniques.
Advanced C++ Memory Management
Memory management is one of the most important topics in C++ programming. Unlike many modern languages, C++ gives programmers direct control over memory allocation and deallocation.
Understanding memory management helps developers create faster, safer, and more efficient applications.
Topics Covered
- Program Memory Layout
- Stack Memory
- Heap Memory
- Static Memory
- Dynamic Memory Allocation
- new and delete Operators
- Memory Leaks
- Dangling Pointers
- Smart Pointers
- RAII Principle
- Memory Optimization Techniques
Understanding C++ Memory Layout
When a C++ program runs, memory is divided into different sections. Each section has a specific purpose.
| Memory Area | Purpose |
|---|---|
| Code Segment | Stores executable program instructions |
| Stack | Stores local variables and function calls |
| Heap | Stores dynamically allocated memory |
| Data Segment | Stores global and static variables |
| Constant Segment | Stores constant values |
Stack Memory in C++
Stack memory is automatically managed by the compiler. Variables created inside functions are stored in stack memory.
Example:
#include<iostream>
using namespace std;
void display()
{
int number = 100;
cout << number;
}
int main()
{
display();
return 0;
}
The variable number is created when the function starts and destroyed automatically when the function ends.
Advantages of Stack Memory
- Very fast access
- Automatically managed
- No memory leaks
- Simple allocation
Limitations of Stack Memory
- Limited size
- Cannot store very large data
- Lifetime is limited to function scope
Heap Memory in C++
Heap memory is used when memory needs to exist beyond the current function execution. It is manually managed by programmers.
Example:
int *ptr = new int; *ptr = 50; cout << *ptr; delete ptr;
The new operator allocates memory and delete releases it.
Dynamic Memory Allocation
Dynamic memory allocation allows creating variables during program execution.
Creating Dynamic Variable
int *number = new int(100); cout << *number; delete number;
Dynamic Array Allocation
int size = 5;
int *arr = new int[size];
for(int i=0;i<size;i++)
{
arr[i]=i+1;
}
delete[] arr;
new and delete Operators
| Operator | Purpose |
|---|---|
| new | Allocates memory dynamically |
| delete | Releases single object memory |
| delete[] | Releases array memory |
Memory Leak in C++
A memory leak happens when dynamically allocated memory is not released after use. The program loses access to that memory, causing unnecessary memory consumption.
Example of Memory Leak:
void function()
{
int *ptr = new int(100);
}
Here memory is allocated but never deleted.
Correct Approach:
void function()
{
int *ptr = new int(100);
delete ptr;
}
Dangling Pointer in C++
A dangling pointer is a pointer that points to memory which has already been released.
Example:
int *ptr = new int(50); delete ptr; cout << *ptr;
After delete, ptr still stores the old memory address.
Solution:
delete ptr; ptr = nullptr;
Smart Pointers in Modern C++
Modern C++ provides smart pointers that automatically manage memory. They prevent memory leaks and dangling pointers.
Types of Smart Pointers
| Smart Pointer | Description |
|---|---|
| unique_ptr | Single owner pointer |
| shared_ptr | Multiple owners share memory |
| weak_ptr | Non-owning reference |
unique_ptr Example
#include<iostream>
#include<memory>
using namespace std;
int main()
{
unique_ptr<int> ptr = make_unique<int>(100);
cout << *ptr;
return 0;
}
Memory is automatically released when ptr goes out of scope.
shared_ptr Example
#include<iostream>
#include<memory>
using namespace std;
int main()
{
shared_ptr<int> ptr1 = make_shared<int>(500);
shared_ptr<int> ptr2 = ptr1;
cout << *ptr2;
}
Both pointers share ownership of the same memory.
RAII Principle in C++
RAII means:
Resource Acquisition Is Initialization
In RAII, resources are acquired during object creation and automatically released when objects are destroyed.
Examples:
- Smart pointers
- File streams
- Mutex locks
Memory Optimization Techniques
- Avoid unnecessary dynamic memory allocation
- Prefer stack allocation when possible
- Use smart pointers instead of raw pointers
- Use move semantics instead of copying large objects
- Release unused resources quickly
- Avoid memory fragmentation
- Use const references for large objects
Common Memory Management Mistakes
| Mistake | Problem |
|---|---|
| Forgetting delete | Memory leak |
| Using deleted pointer | Dangling pointer |
| Deleting same memory twice | Undefined behavior |
| Accessing array outside size | Memory corruption |
C++ Memory Management Interview Questions
- Difference between stack and heap memory?
- What is dynamic memory allocation?
- Explain new and delete operators.
- What is a memory leak?
- What is a dangling pointer?
- Why are smart pointers used?
- Difference between unique_ptr and shared_ptr?
- Explain RAII in C++.
- What happens if memory is not released?
- How can you optimize memory usage?
Summary
Advanced memory management is a core C++ skill. Understanding stack, heap, pointers, smart pointers, and optimization techniques helps developers write high-performance and reliable applications.
Comments
Post a Comment