Getting Started
What is C++?
- C++ was developed by Bjarne Stroustrup as an extension of the C language.
- Despite originating in the 1980s, C++ has consistently remained a popular and influential programming language.
- C++ offers cross-platform compatibility, allowing developers to create high-performance applications and software systems.
- C++ is known for its close proximity to hardware, enabling programmers to issue instructions directly to the system, bypassing intermediaries, and gaining substantial control over system resources and memory.
- C++ boasts a rich ecosystem of libraries and frameworks that expedite development by providing pre-built components for various tasks.
Why one should learn C++?
Versatile Application:
- C++ boasts exceptional versatility and finds applications in a myriad of fields, promising diverse career opportunities. Its adaptability transcends industries like finance, gaming, and healthcare, offering an abundance of career pathways.
Strong Foundation and Skill Enhancement:
- Learning C++ establishes a robust programming foundation, which serves as a launchpad for mastering other programming languages. It equips individuals with invaluable problem-solving skills and fosters logical thinking, elevating their overall programming proficiency.
Efficiency and Performance Focus:
- C++ is synonymous with the creation of efficient, high-performance code. Its unwavering emphasis on optimization and resource management proves indispensable when crafting software that excels in both speed and resource utilization.
Cross-Platform Prowess:
- C++ is renowned for its seamless cross-platform compatibility, enabling developers to create software that seamlessly operates across different operating systems. This broadens your software’s reach and impact.
Rich Library Ecosystem for Productivity:
- C++ offers a wealth of libraries, including stalwarts like STL and Qt, which expedite development by providing pre-built solutions for common tasks. This resourcefulness saves considerable time and effort that would otherwise be invested in coding from scratch.
High Demand and Career Prospects:
- Proficiency in C++ is perpetually sought after across industries. Employers highly value developers capable of producing efficient and reliable code, offering a plethora of career opportunities and job security.
Wide Industry Usage Demonstrates Reliability:
- C++ is prominently employed in pivotal industries such as finance and gaming, underscoring its adaptability and reliability as a programming language. This widespread adoption cements its status as a dependable choice.
Career Growth and Specialization:
- Mastery of C++ serves as a gateway to advanced career prospects. With experience, individuals can specialize in specialized domains such as game engine development, real-time systems, or financial software, offering exciting and fulfilling career pathways.
C++ Programming Language Features
Proficient in Object-Oriented Concepts:
- C++ exhibits adeptness in the realm of object-oriented programming, harnessing concepts like encapsulation, inheritance, and polymorphism to facilitate a structured and organized approach to code development.
Comprehensive Toolbox:
- Within its standard library, C++ offers an extensive array of functions and tools, affording programmers a resourceful arsenal that simplifies the execution of diverse programming tasks.
Template-Driven Versatility:
- C++ possesses the capability to create adaptable tools and classes using templates, enabling code to seamlessly adjust to varying contexts and requirements.
Mastery in Error Management:
- It excels as a safety net, demonstrating prowess in error handling to ensure the graceful and uninterrupted operation of programs, bolstering reliability.
Balanced Proficiency:
- C++ showcases a remarkable equilibrium, making it equally adept in complex software development and lower-level tasks, thus rendering it a versatile programming language.
Empowered with Pointers:
- C++ endows developers with potent pointer mechanisms, elevating resource management and enabling seamless communication with hardware components.
Efficient Memory Administration:
- Its acumen extends to the efficient administration of computer memory, mitigating waste and inefficiency, thereby fostering optimized program performance.
Seamless Integration with C:
- C++ harmoniously integrates with its predecessor, C, ensuring the seamless interplay of code and offering an expedited pathway to code reuse and integration.
Top 5 IDEs and Code Editors for C++
Using an Integrated Development Environment (IDE) or a code editor in C++ is crucial for several reasons, and it greatly enhances the development process. Here are the top 5 IDEs and code editors for C++, along with a brief explanation of why they are essential:
1. Visual Studio (Microsoft):
- Visual Studio is a comprehensive IDE with advanced debugging and code analysis tools. It streamlines C++ development by offering features like code completion and refactoring, making it an efficient choice for C++ programmers.
2. CLion (JetBrains):
- CLion is renowned for its intelligent code analysis and cross-platform support. It enhances productivity through features like integrated CMake support and a robust debugger, facilitating smooth C++ development.
3. Code::Blocks:
- Code::Blocks is a versatile, open-source code editor with a simple and intuitive interface. It offers a range of plugins for added functionality, making it an excellent choice for beginners and those who prefer a lightweight development environment.
4. Eclipse CDT (Eclipse Foundation):
- Eclipse CDT is a mature IDE with a rich ecosystem of plugins. It’s valuable for large-scale C++ projects due to its extensibility and cross-platform compatibility.
5. Xcode (Apple):
- Xcode is indispensable for macOS and iOS development but also supports C++. It provides a unified development environment for Apple platforms, including a C/C++ compiler, making it a top choice for Apple-centric C++ development.
Basic Structure of C++
Preprocessor Directives:
- These are instructions for the preprocessor to handle before compilation.
- Commonly used for including header files with #include
- For example,
#include
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Namespace Declarations:
- Namespaces help organize code and prevent naming conflicts.
- The using namespace statement allows access to the members of a namespace without specifying the namespace each time.
- For example,
#include
using namespace std; // This allows using std:: prefix for standard C++ features
int main() {
cout << "Hello, World!" << endl; //Using cout and endl directly
return 0;
}
Main Function:
- Every C++ program must have a main() function, which serves as the entry point for the program.
- It returns an integer value (int) to indicate the status of the program to the operating system.
- For example,
int main() {
return 0; // Indicates successful program execution
}
Function Definitions:
- Functions encapsulate specific actions and can be defined before or after the
main()
function. - Functions are defined with a return type, a name, optional parameters, and a body containing the actual code.
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(10, 15);
return 0;
}
Variable Declarations:
- Variables are used to store data of different types such as integers, characters, floats, etc.
- They need to be declared with a data type and can optionally be initialized with a value.
- For example,
int age = 25; // Declaration and initialization of an integer variable
char grade = 'A'; // Declaration and initialization of a character variable
Statements and Expressions:
- Statements are individual instructions or actions that make up a program.
- Expressions are combinations of operators and operands that produce a result.
- For example,
int a = 10; // Statement: variable declaration
int b = 5; // Statement: variable declaration
int sum = a + b; // Expression: addition of 'a' and 'b'
Comments:
- Comments provide additional information, explanations, or annotations within the code.
- Single-line comments start with
//
and extend to the end of the line. - Multi-line comments start with
/*
and end with*/
. - For example,
// Single-line comment
/*
This is a
multi-line comment.
*/
Variables
C++ variables act as dynamic containers, holding data of different types, from numbers to text. In C++, there are several types of variables:
Types Of Variables
- Integer Variables (int): These store whole numbers like 42 or -10.
- Floating-Point Variables (float and double): These hold numbers with decimal points, like 3.14 or -0.005. “float” stores smaller decimal numbers, while “double” stores larger and more precise ones.
- Character Variables (char): These store single characters, such as ‘A’ or ‘$’.
- Boolean Variables (bool): They store only two values: “true” or “false,” representing binary choices.
- String Variables (string): These hold sequences of characters, like “Hello, World!”
- Array Variables: Arrays store multiple values of the same data type in a single variable. For example, an array of integers could store [1, 2, 3, 4, 5].
- Pointer Variables: Pointers store memory addresses of other variables. They are used for more advanced operations in C++.
Rules For Naming Variables
- Start with a letter (A-Z or a-z) or an underscore (_).
- Follow the initial character with letters, digits (0-9), or underscores.
- Avoid using C++ reserved words (like “int,” “float,” etc.) as variable names.
- Variable names are case-sensitive; “myVariable” and “myvariable” are different names.
- Use meaningful names that describe the variable’s purpose or content.
- Use camelCase or snake_case for multi-word variable names.
- Avoid using special characters like @, $, and % in variable names.
- Keep variable names reasonably short and concise, but not overly abbreviated.
- Use lowercase letters for variable names (it’s a common convention).
Scope Of C++ Variables
In C++, variables can be categorized based on their scope into the following main types:
Local Variable
- Definition: Local variables are declared within a specific block of code, such as within a function, a loop, or a conditional statement.
- Scope: The scope of a local variable is limited to the block or function in which it is defined. It starts when the variable is declared and ends when the block or function completes execution.
- Lifetime: The lifetime of a local variable is tied to the scope in which it is defined. When the scope ends (e.g., the function exits), the variable is destroyed and its memory is released.
#include
int main() {
int localVariable = 20; // Local variable
std::cout << "Local variable: " << localVariable << std::endl;
return 0;
}
Output:
Local variable: 20
Global Variable
- Definition: Global variables are declared outside of any function or block, typically at the beginning of the program, before any functions are defined.
- Scope: The scope of a global variable is the entire program. It can be accessed and modified from any part of the program, including functions.
- Life time: The lifetime of a global variable is throughout the execution of the program. It is allocated when the program starts and deallocated when the program ends..
#include
int globalVariable = 10; // Global variable
int main() {
std::cout << "Global variable: " << globalVariable << std::endl;
return 0;
}
Output:
Global variable: 10
Constants
In C++, constants are essentially variables whose values remain unchanged after they are initially assigned. These values are explicitly specified in the program and can be of various types, including integers, floats, characters, and more. For example,
#include
int main() {
const int MAX_SCORE = 100; //Constant
const double PI = 3.14159; //Constant
std::cout << "Maximum score: " << MAX_SCORE << std::endl;
std::cout << "Value of PI: " << PI << std::endl;
return 0;
}
Output:
Maximum score: 100
Value of PI: 3.14159
Data types
In C++, data types are used to specify the type of data that a variable can hold. They define the size and format of the data stored in memory.
Fundamental Data Types
The Table below shows the fundamental datatypes in C++.
T1.Fundamental Data Types
Data Type | Description | Size | Range |
---|---|---|---|
int | Signed Integer | 4 bytes | -9.22e18 to 9.22e18 (64-bit systems) |
short | Short Integer | 2 bytes | -3.27e4 to 3.27e4 |
long | Long Integer | 4 bytes | -9.22e18 to 9.22e18 (64-bit systems) |
long long | Very Long Integer | 8 bytes | -9.22e18 to 9.22e18 |
float | Single-Precision Floating-Point | 4 bytes | -3.4e38 to 3.4e38 |
double | Double-Precision Floating-Point | 8 bytes | -1.8e308 to 1.8e308 |
long double | Extended-Precision Floating-Point | Platform-dependent | Implementation-dependent |
signed char | Signed Character | 1 byte | -1.28e2 to 1.27e2 |
unsigned char | Unigned Character | 1 byte | 0 to 2.55e2 |
bool | Boolean | 1 byte | true or false |
let’s discuss the fundamental data types with examples:
int (Signed Integer):
- Meaning: int represents signed integers, which can be both positive and negative whole numbers.
- Size: 4 bytes on most systems (32 bits).
- Range: Approximately -2.14e9 to 2.14e9 on a typical 32-bit system.
- Example:
int myNumber = 42;
short (Short Integer)
- Meaning: Used for short integers within a limited range.
- Size: 2 bytes (16 bits).
- Range: Approximately -32,768 to 32,767.
- Example:
short temperature = -150;
long (Long Integer)
- Meaning: Represents long integers, suitable for large whole numbers.
- Size: 4 bytes on most systems (32 bits).
- Range: Approximately -2.14e9 to 2.14e9 on a typical 32-bit system.
- Example:
long population = 7800000000;
long long (Very Long Integer)
- Meaning:
long long
is used for very long integers, often for extremely large values. - Size: 8 bytes (64 bits).
- Range: Approximately -9.22e18 to 9.22e18.
- Example:
long long universeAge = 13800000000;
float (Single-Precision Floating-Point)
- Meaning: Represents single-precision floating-point numbers with moderate precision for real numbers.
- Size: 4 bytes (32 bits).
- Range: Approximately -3.4e38 to 3.4e38.
- Example:
float piValue = 3.1415927f;
double (Double-Precision Floating-Point)
- Meaning: Represents double-precision floating-point numbers with higher precision.
- Size: 8 bytes (64 bits).
- Range: Approximately -1.8e308 to 1.8e308.
- Example:
double Value = 1234.56789;
double myNumber = 1234.56789;
long double (Extended-Precision Floating-Point)
- Meaning: Represents extended-precision floating-point numbers, often platform-dependent with even higher precision.
- Size: Platform-dependent.
- Range: Implementation-dependent.
- Example:
long double highPrecisionValue = 0.12345678901234567890L;
signed char (Signed Character)
- Meaning: Represents signed characters as integers, allowing both positive and negative character values.
- Size: 1 byte (8 bits).
- Range: Approximately -128 to 127.
- Example:
signed char grade = 'A';
unsigned char (Unsigned Character)
- Meaning: Represents unsigned characters as integers, with values ranging from 0 to 255.
- Size: 1 byte (8 bits).
- Range: 0 to 255.
- Example:
unsigned char brightness = 200;
bool (Boolean)
- Meaning: Represents Boolean values and has only two possible values,
true
orfalse
, used for logical conditions. - Size: 1 byte (8 bits).
- Range: true or false.
- Example:
bool isSunny = true;
Datatype Modifiers:
In C++, datatype modifiers are used to alter the properties of basic data types like int, float, char, etc. They allow you to specify the storage size and sign of variables. The datatype modifiers in C++ are:
- Signed: Variables can represent both positive and negative values.
- Unsigned: Variables can represent only non-negative values (zero and positive values). They use the full range for positive values.
- Short: Reduces the size of variables, often used for small integer values.
- Long: Increases the size of variables, suitable for large values or more significant precision
signed int mySignedInt = -10;
unsigned int myUnsignedInt = 10;
short myShort = 100;
long myLong = 10000;
Type Conversions:
Type conversions in C++ involve changing the data type of a variable or expression. There are two main types of type conversions:
Implicit Type Conversion (Coercion):
- Automatically performed by the compiler when an expression involves different data types.
- Generally, it’s a widening conversion, ensuring that data loss doesn’t occur.
- Example:
int myInt = 10;
float myFloat = 5.5;
float result = myInt + myFloat; // Implicitly converts myInt to float before addition.
Explicit Type Conversion (Casting):
- Programmer explicitly specifies the type conversion using casting operators.
- It can be used for narrowing conversions, but you should be cautious about potential data loss.
double myDouble = 5.7;
int myInt = static_cast(myDouble); // Explicitly converts double to int.
Operators
In C++, operators are special symbols or keywords that are used to perform operations on variables and values. They allow you to manipulate data, perform calculations, and make decisions in your programs. Operators are a fundamental part of C++ and are categorized into various types based on their functionality. There are six types of operators in C++. Those are:
Arithmetic Operators:
These operators perform basic mathematical operations like addition, subtraction, multiplication, division, and more.
Example:
int a = 10;
int b = 5;
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
Relational Operators:
These operators are used to compare values and return a Boolean result (true or false). They include equality, inequality, greater than, less than, and more.
Example:
int x = 10;
int y = 20;
bool isEqual = (x == y); // Equality check
bool isGreater = (x > y); // Greater than check
Logical Operators:
Logical operators are used for combining and manipulating Boolean values. They include logical AND, logical OR, and logical NOT.
Example:
bool isSunny = true;
bool isWarm = false;
bool isGoodWeather = isSunny && isWarm; // Logical AND
bool isAcceptable = isSunny || isWarm; // Logical OR
Assignment Operators:
These operators assign values to variables. The most common is the simple assignment operator =
.
Example:
int num = 42; // Assignment
Increment and Decrement Operators:
These operators are used to increase or decrease the value of a variable.
Example:
int count = 5;
count++; // Increment by 1
count--; // Decrement by 1
Conditional (Ternary) Operator:
The ternary operator is a conditional operator, also known as the conditional expression. It allows you to evaluate a condition and choose one of two values based on whether the condition is true or false. The ternary operator has the following syntax:
(condition) ? (value_if_true) : (value_if_false)
- Here’s an example of the ternary operator in C++
#include
using namespace std;
int main()
{
float Exam_Score;
cout<<"Enter your Exam_Score:"<>Exam_Score;
string result;
result=(Exam_Score>30)? "You have passed":"You have failed";
cout<<":Result:"<
Enter your Exam_Score:45
Result:You have passed
................................................................
Enter your Exam_Score:29
Result:You have failed
console.log( 'Code is Poetry' );
Bitwise Operators:
These operators perform operations at the binary level. They include bitwise AND, OR, XOR, and more.
Example:
int x = 5; // Binary: 0101
int y = 3; // Binary: 0011
int bitwiseAnd = x & y; // Bitwise AND (0001)
int bitwiseOr = x | y; // Bitwise OR (0111)
Flow Control
C++ practitioners harness these flow control tools to craft meticulously structured and high-performing software solutions capable of adeptly managing diverse scenarios, orchestrating intelligent decision-making processes, and executing repetitive operations as necessitated. The selection of an appropriate flow control structure is intricately tied to the unique logic and prerequisites of the specific software project. C++ flow control is fundamentally categorized into three core types: Conditional Statements, Looping Statements, and Transfer Statements.
Conditional Statements
Conditional statements are fundamental constructs in programming that allow you to make decisions in your code. They enable your program to execute different code blocks based on whether certain conditions are met. Conditional statements are essential for creating responsive and intelligent programs.
In C++, there are primarily two types of conditional statements: if
statements and switch
statements.
If Statement
The if statement is the most basic form of a conditional statement. It allows you to execute a block of code if a specified condition is true. You can also use else and else if clauses to handle scenarios when the condition is false or when there are multiple conditions to check.
The basic structure of an if statement is as follows:
if (condition) {
// Code to execute if the condition is true
} else if (another_condition) {
// Code to execute if the 'another_condition' is true
} else {
// Code to execute if none of the conditions are true
}
Example : The example below shows the most basic form of an if statement. This code aims to determine whether the variable x is greater than y or not.
#include
using namespace std;
int main()
{
int x =20;
int y=10;
if (x>y){
cout<<"x is greater than y"<
Output:
x is greater than y
Example: The C++ program below prompts the user to input a score and then assigns a grade based on the score’s range, displaying the corresponding grade (F, D, C, B, or A) according to specified score intervals. For instance, if the score is below 30, it displays an F Grade, while scores between 60 and 75 result in a B Grade, and scores of 75 or higher receive an A Grade.
#include
using namespace std;
int main()
{
float score; // Declare a floating-point variable
cout<<"Enter the score within the range [0-100]:"<>score;
if (score<30){ // If the score is less than 30, display "F Grade."
cout<<"F Grade"<=30 && score<45){ // If the score is between 30 and 45, display "D Grade."
cout<<"D Grade"<=45 && score<60){ // If the score is between 45 and 60, display "C Grade."
cout<<"C Grade"<=60 && score<75){ // If the score is between 60 and 75, display "B Grade."
cout<<"B Grade"<=75){ // If the score is greater than or equal to 75 display "A Grade."
cout<<"A Grade"<
Output:
Enter the score within the range [0-100]:
67
B Grade
Example: The given code is an example of nested if-else statements in C++. A nested if-else statement is a control flow structure in computer programming, particularly in languages like C++, where an if-else statement is placed inside another if or else block, allowing for more complex decision-making logic. In this example, if the value of x is greater than y, and if it is, it further checks whether x is even or not using a nested if statement. Based on the results of these checks, it prints one of three possible messages. If x is not greater than y, it simply prints “x is not greater than y.
#include
using namespace std;
int main()
{
int x=30;
int y=25;
if (x>y){
if(x%2==0)
{
cout<<"x is greater than y and even"<
Output:
x is greater than y and even
Switch Statements
A switch statement is a control flow statement in C++ that allows you to select one of many code blocks to be executed based on the value of an expression. It is particularly useful when you have multiple cases to consider and simplifies the code compared to using a series of nested if-else statements.
switch (expression) {
case constant1:
// Code block executed when 'expression' matches 'constant1'.
break;
case constant2:
// Code block executed when 'expression' matches 'constant2'.
break;
// Additional case labels...
default:
// Code block executed when 'expression' doesn't match any case label.
}
Example: The following code demonstrates the usage of a switch statement.
#include
using namespace std;
int main()
{
// Traffic Light Simulator
int lightColor;
// Display menu for selecting light colors
cout << "Red [1]" << endl << "Yellow [2]" << endl << "Green [3]" << endl;
cout << "Enter the light color (1-3): ";
// Input the chosen light color
cin >> lightColor;
// Check the selected light color and provide an appropriate response
switch (lightColor)
{
case 1:
cout << "Stop! The light is red" << endl;
break;
case 2:
cout << "Prepare to Stop! The light is Yellow" << endl;
break;
case 3:
cout << "GO! The light is green" << endl;
break;
default:
cout << "Invalid input. Please select a valid light color (1-3)." << endl;
break;
}
return 0;
}
Red [1]
Yellow [2]
Green [3]
Enter the light color (1-3):
1
Stop! The light is red
Explanation:
- The code simulates a traffic light scenario, where the user is prompted to select a light color.
- It displays a menu for the user to choose from Red (1), Yellow (2), or Green (3).
- Depending on the user’s choice, it provides an appropriate response, such as “Stop!” for red, “Prepare to Stop!” for yellow, and “GO!” for green.
- If the user enters an option outside the range (1-3), the code displays “Invalid input. Please select a valid light color.”
Looping Statements
- A C++ loop statement allows you to execute a block of code repeatedly, either based on a specified condition or for a predetermined number of iterations.
- This feature is vital for automating repetitive tasks and handling scenarios where you need to perform the same set of actions multiple times.
- The main types of C++ loop statements include the ‘for’ loop, ‘while’ loop, and ‘do-while’ loop, each offering unique ways to control and manage the flow of program execution through iteration
For Loop
The ‘for’ loop is a fundamental and versatile control structure in C++, used to execute a block of code repeatedly for a specified number of iterations. The syntax of a ‘for’ loop consists of three essential components:
- Initialization: A statement that sets the loop control variable to an initial value.
- Condition: An expression that is evaluated before each iteration. If it’s true, the loop continues; if it’s false, the loop terminates.
- Update: A statement that modifies the loop control variable after each iteration.
for (initialization; condition; update) {
// Code to be executed in each iteration
}
Example: The C++ code below demonstrates a ‘for’ loop that initializes a variable ‘i’ to 0, increments it by 1 in each iteration, and displays the doubled value of ‘i’ in the console. This loop repeats this process five times, producing an output sequence showing the values of ‘i’ multiplied by 2 from 0 to 8.
#include
using namespace std;
int main() {
// A 'for' loop to repeat a set of instructions
for (int i = 0; i < 5; i++) {
// Display the doubled value of 'i'
cout << "The value of i: " << i * 2 << endl;
}
return 0;
}
Output:
The value of i: 0
The value of i: 2
The value of i: 4
The value of i: 6
The value of i: 8
Example: This example below calculates the sum of even numbers from 2 to a positive integer ‘N’ entered by the user. It uses a ‘for’ loop to iterate through even numbers, accumulates them in the ‘sum’ variable, and displays the final sum. The user is prompted to input ‘N’ to define the range of even numbers to consider.
#include
using namespace std;
int main() {
int N, sum = 0;
// Input: Prompt user for a positive integer 'N'
cout << "Enter a positive integer N: ";
cin >> N;
// Loop through even numbers and calculate their sum
for (int i = 2; i <= N; i += 2) {
sum += i; // Accumulate even numbers in 'sum'
}
// Output: Display the sum of even numbers
cout << "Sum of even numbers from 2 to " << N << ": " << sum << endl;
return 0;
}
Output:
Enter a positive integer N: 10
Sum of even numbers from 2 to 10: 30
Example: The example below, employs a range-based for loop to iterate through the elements of the ‘data’ array, printing each element’s value to the console. This loop simplifies the process of iterating through arrays, making it easier to access and manipulate array elements.
#include
using namespace std;
int main() {
int data[] = {1, 2, 3, 4, 5};
// Use a range-based for loop to iterate through the 'data' array
for (int i : data) {
// Print the value of 'i' in each iteration
cout << "Value of i: " << i << endl;
}
return 0;
}
Output:
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
While loop
The ‘while’ loop is a fundamental construct in C++ programming that enables the repetitive execution of code as long as a given condition remains true. A ‘while’ loop has a straightforward syntax:
while (condition) {
// Code to be executed as long as the condition is true
}
Example:
The code below features a ‘while’ loop that initializes a variable ‘i’ to 0 and repeatedly prints the value of ‘i’ to the console in each iteration, incrementing ‘i’ by 1. The loop continues until ‘i’ reaches or exceeds the value of 5, creating an output that displays the values of ‘i’ from 0 to 4.
#include
using namespace std;
int main() {
int i = 0;
// Loop continues while 'i' is less than 5
while (i < 5) {
// Display the value of 'i'
cout << "Value of i: " << i << endl;
i++; // Increment 'i'
}
return 0;
}
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Do-While Loop
A do-while loop in C++ is a control structure that repeatedly executes a block of code as long as a specified condition remains true. The key difference between a do-while loop and a while loop is that in a do-while loop, the code block is executed at least once before checking the loop condition. A do-while loop has the following syntax:
do {
// Code to be executed
} while (condition);
Example: The code below, utilizes a do-while loop to ensure the display of the value of ‘i’ from 0 to 5. It increments ‘i’ in each iteration and continues as long as ‘i’ remains less than or equal to 5.
#include
using namespace std;
int main() {
int i = 0;
// Start a do-while loop to display 'i' and increment it
do {
cout << "The value of i: " << i << endl;
i++; // Increment 'i' for the next iteration
} while (i <= 5); // Continue the loop while 'i' is less than or equal to 5
return 0;
}
Transfer Statements
Transfer statements in C++ enable the regulation of program flow by redirecting control to various sections of the code. The primary types of transfer statements include the Break Statement and Continue Statement.
Break Statement
The break
statement in C++ is used to exit from a loop prematurely, terminating the loop’s execution, and transferring control to the statement immediately following the loop.
Example:
This code below uses a ‘for’ loop to count from 0 to 10. When ‘i’ reaches 4, the ‘break’ statement is executed, terminating the loop and printing “Breaking the loop at i=4.” The program then displays “The loop is terminated”.
#include
using namespace std;
int main() {
for (int i = 0; i <= 10; i++) {
if (i == 4) {
// Display a message when breaking the loop at i=4
cout << "Breaking the loop at i=4." << endl;
break;
}
// Display the current value of i during each iteration
cout << "i: " << i << endl;
}
// Indicate that the loop has terminated
cout << "The loop is terminated." << endl;
return 0;
}
Output:
i: 0
i: 1
i: 2
i: 3
Breaking the loop at i=4.
The loop is terminated.
Continue Statement
Example: In the code below, a ‘for’ loop iterates from 1 to 10. When a number is divisible by 3, the ‘continue’ statement is executed, skipping that iteration and printing all other numbers.
#include
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
// Skip numbers divisible by 3
continue;
}
cout << "i: " << i << endl;
}
return 0;
}
Output:
i:1
i:2
i:4
i:5
i:7
i:8
i:10
Functions
A function is a self-contained block of code that performs a specific task or a set of related tasks. Think of functions as mini-programs within your main program. They take some input, perform operations, and may return a result.
Benefits of Using Functions:
- Modularity: Functions break down complex tasks into manageable parts.
- Reusability: You can call a function multiple times with different inputs.
- Readability: Functions make your code more organized and easier to understand.
Types of Functions:
C++ supports various types of functions:
- Standard Functions: Built-in functions like
sqrt
orstrlen
. - User-Defined Functions: Functions you create for specific tasks.
Standard Functions
Standard functions are functions that come pre-defined with C++ and are part of the C++ Standard Library. They provide a wide range of commonly used operations, allowing you to perform tasks without having to write the code from scratch. To call standard functions in C++, you need to include the relevant header files that correspond to the functions you want to use. Here are some common headers and their purposes:
#include // For input and output functions
#include // For mathematical functions
#include // For string manipulation functions
#include // For working with the STL vector container
#include // For file input and output operations
#include // For time and date-related functions
#include // For general-purpose functions like memory allocation and random number generation
#include // For string handling and manipulation, including the string class
#include // For using algorithms like sort and find on containers
Example:
This code calculates the square root of a given number (16.0) using the sqrt() function from the <cmath> header, and then it displays the result. The #include <cmath> statement includes the necessary header, enabling the use of mathematical functions in the program.
#include
#include // Include the cmath header for mathematical functions
using namespace std;
int main() {
double number = 16.0;
// Using the sqrt() function from cmath to calculate the square root
double squareRoot = sqrt(number);
cout << "Square root of " << number << " is: " << squareRoot << endl;
return 0;
}
Output:
Square root of 16 is: 4
User-Defined Functions
A user-defined function is a custom function created by the programmer to perform a specific set of tasks within a program.
- These functions are defined by the user (programmer) and given a unique name. They can accept input values (parameters), execute a series of instructions, and optionally return a result.
- User-defined functions enhance code modularity, making programs more organized and readable, and they can be reused multiple times, promoting efficient and maintainable code.
- In this section, we will discuss various types of user-defined functions.
Void Function
- A void function, as the name suggests, is a function that does not return any value. Instead, it performs a specific task or operation and may involve printing, modifying variables, or executing other instructions.
- To create a void function, you need to define its name, specify its parameters (if any), and write the function’s code to execute the desired task. Please see the syntax below:
void function_name(parameters) {
// Function body
// Perform tasks or operations
// No return statement
}
Example: Here’s an example of a simple void function that displays a greeting:
#include
void greet() {
std::cout << "Hello, World!" << std::endl;
}
int main() {
greet(); // Calling the void function
return 0;
}
Output:
Hello, World!
Functions with Return Values
- Functions with return values are used when you need the function to produce a specific result or value.
- They can be called to obtain a result based on their calculations.
- Please see the syntax below:
return_type function_name() {
// Function body
// Perform operations
return result; // Return the calculated result
}
Example:
Here’s an example of a function that calculates the sum of three numbers and returns the result.
#include
using namespace std;
// Function to compute the sum of three numbers
float computeSum() {
float x = 10.7;
float y = 20.2;
float z = 30.5;
float S = x + y + z;
return S; // Return the computed sum
}
int main() {
float sum = computeSum(); // Call the computeSum function
cout << "The value of sum: " << sum << endl; // Display the sum
return 0;
}
Output:
The value of sum: 61.4
Explanation:
- The code defines a function named computeSum that computes the sum of three predefined floating-point numbers.
- In the main function, it invokes computeSum to calculate the sum and stores the result.
- Finally, the program displays the computed sum to the console.
- This code illustrates how a function with a return value but no parameters can be used to compute and exhibit a specific value.
Function With Parameters:
- Functions with parameters are used when you need to pass data to the function for processing.
- They can accept one or more input values, perform operations on them, and potentially produce a result or side effects.
- Please see the syntax below:
return_type function_name(parameter_type parameter_name) {
// Function body
// Perform operations using the parameter(s)
return result; // Optional, return a value if needed
}
Example: The code below calculates the sum of three floating-point numbers and returns the result.
#include
using namespace std;
// Function definition with parameters
float addFun(float a, float b, float c)
{
// Calculate the sum of the three parameters
float sum = a + b + c;
// Return the computed sum
return sum;
}
int main()
{
// Define three floating-point numbers
float x = 5.3;
float y = 10.4;
float z = 11.7;
// Call the addFun function with the specified values and store the result in 'sum'
float sum = addFun(x, y, z);
// Display the value of 'sum'
cout << "The value of sum: " << sum << endl;
return 0;
}
Output:
The value of sum: 27.4
Explanation:
- The code includes a function addFun that accepts three float parameters and returns their sum.
- Within the main function, this addFun function is called with specific float values, and the result is stored in a variable sum.
- The program then prints the value of sum to the console, displaying the sum of the provided float values
Function Overloading
- Function overloading is a feature that allows you to define multiple functions with the same name within the same scope.
- These functions must have different parameter lists, which means they accept a different number of parameters or parameters of different data types.
Example: Here’s a simple example to illustrate function overloading:
#include
using namespace std;
// Function to add two integers
int add_fun(int a, int b) {
return a + b;
}
// Function to add three integers
int add_fun(int a, int b, int c) {
return a + b + c;
}
// Function to add two floats
float add_fun(float a, float b) {
return a + b;
}
int main() {
int x = 10;
int y = 20;
int z = 30;
float u = 22.57;
float v = 33.16;
// Call the first overloaded function and display the result
int sum1 = add_fun(x, y);
cout << "The value of sum1: " << sum1 << endl;
// Call the second overloaded function and display the result
int sum2 = add_fun(x, y, z);
cout << "The value of sum2: " << sum2 << endl;
// Call the third overloaded function and display the result
float sum3 = add_fun(u, v);
cout << "The value of sum3: " << sum3 << endl;
return 0;
}
Explanation:
- The code demonstrates function overloading in C++, where multiple functions have the same name but differ in the number or type of their parameters.
- There are three overloaded functions: add_fun for adding two integers, add_fun for adding three integers, and add_fun for adding two floats.
- In the main function, each overloaded function is called with appropriate arguments, and their results are displayed. This showcases how C++ selects the correct function based on the argument types during function calls.
Recursive function
- Recursive functions are functions that call themselves during their execution.
- This technique is often used to solve problems by dividing them into smaller, identical subproblems.
- Each subproblem is solved using the same function, and the results are combined to solve the original problem.
- The syntax of recursion in C++ involves defining a function that calls itself, typically to solve a problem by breaking it down into smaller, similar sub-problems. Here’s the basic structure for a recursive function in C++:
void recursiveFunction() { // Definition of a recursive function
// Base case: The stopping condition
recursiveFunction(); // Recursive call to itself
}
int main() {
recursiveFunction(); // Calling the recursive function
}
Example:
Here is a simple example of a recursive function in C++. This function calculates the factorial of a non-negative integer.
#include
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: Factorial of 0 or 1 is 1.
} else {
return n * factorial(n - 1); // Recursive case: n! = n * (n-1)!
}
}
int main() {
int num = 5;
int result = factorial(num);
cout << "Factorial of " << num << " is " << result << endl;
return 0;
}
Output:
Factorial of 5 is 120
Explanation:
- This code above defines a recursive function called factorial, which calculates the factorial of a given input number n. Factorial is the product of all positive integers from 1 to n.
- The function checks if n is equal to 0 or 1, as this serves as the base case. If n is 0 or 1, the function returns 1 since the factorial of 0 or 1 is defined as 1.
- For values of n greater than 1, the function makes a recursive call to itself. It calculates the factorial by multiplying n with the factorial of n – 1, and this process continues until it reaches the base case.
- The final result of the factorial function is the factorial of the input number n. In the main function, this factorial function is called with num set to 5, and the result is printed to the console, confirming that the factorial of 5 is indeed 120.
Inline Function
- Inline functions are a way to optimize code execution by expanding the function’s body at the location where it’s called rather than executing a separate function call.
- During compilation, an inline function replaces the function call with the actual function code at the calling point.
- They are suitable for small, frequently used functions that are called throughout the program.
- Inline functions are used to enhance program performance by reducing the overhead of function calls.
Syntax Of Inline Function
inline return_type function_name(parameters) {
// Function body
// ...
}
Example:
Here’s an example of an inline function that calculates the square of a number.
#include
using namespace std;
// Inline function to calculate the square of a number
inline int square(int x) {
return x * x;
}
int main() {
int num = 5;
int result = square(num); // Function call is replaced with the square of num
cout << "Square of " << num << " is " << result << endl;
return 0;
}
Lambda Functions
Lambda functions, also known as lambda expressions, are a powerful feature in C++. They allow you to create small, inline functions right where you need them.
Key Features of Lambda Functions:
Anonymous Functions: Lambda functions are anonymous, meaning they don’t have a formal name like regular functions.
Inline Definition: Lambda functions are defined directly within the code where they are used, making your code more compact and readable.
Capture Lists: Lambda functions can capture and use variables from their surrounding scope. This feature is handy when you want to operate on external variables within the lambda.
Syntax of a Lambda Function:
[ captures ] ( parameters ) -> return_type {
// Function body
}
- [ captures ]: This part allows you to capture variables from the surrounding scope. You can specify which variables the lambda function should use.
- ( parameters ): These are the parameters that the lambda function takes, similar to regular function parameters.
- -> return_type: This part specifies the return type of the lambda function.
- { … }: Here, you place the actual code that the lambda function will execute.
Let us explore various types of Lambda functions with examples:
Lambda with No Capture and No Parameters
#include
int main() {
auto myFun = [] {
return 42;
};
int result = myFun();
std::cout << "Result: " << result << std::endl;
return 0;
}
Output:
Result: 42
Explanation
- The code defines a lambda function named myFun using the auto keyword, implying that the return type is automatically deduced.
- This lambda takes no parameters and doesn’t capture any external variables, as seen from the empty () and [].
- The lambda’s body contains a single statement that returns the integer 42, and when the lambda is called, it returns this value. The code prints the result “Result: 42″ to the console.
Lambda Capturing External Variable (No Parameters, Capture by Reference)
#include
int main() {
int x = 10;
auto myFun = [&x] {
x += 20;
};
myFun();
std::cout << "Sum: " << x << std::endl;
return 0;
}
Output:
Sum: 30
Explanation
- In this code, a lambda function named myFun is defined within the main function. The lambda has no parameters, as indicated by ().
- Inside the lambda, it captures the variable x by reference using [&x], which means it can access and modify the x variable from the enclosing scope.
- The lambda’s body increments the value of x by 20. When myFun() is called, it modifies the original value of x, changing it to 30. The code then prints the updated value with “Sum: 30” to the console
Lambda with Parameters
#include
int main() {
auto add = [](int a, int b) {
return a + b;
};
int result = add(5, 7);
std::cout << "Sum: " << result << std::endl;
return 0;
}
Output:
Sum: 12
Explanation:
In the above code, the lambda function takes two integer parameters a and b, and returns their sum.
After defining the lambda function, it is called with values 5 and 7 as arguments, and the result is stored in the result variable. This results in the lambda adding 5 and 7, which equals 12.
Lambda Capturing All Variables by Value
#include
int main() {
int x = 5;
int y = 7;
auto myFun = [=] {
return x + y;
};
int result = myFun();
std::cout << "Sum: " << result << std::endl;
return 0;
}
Output:
Sum: 12
Explanation:
- The code declares two integer variables, x and y, with values 5 and 7.
- It defines a lambda function myFun using [=], which captures all variables in the current scope by value, meaning it captures the values of x and y.
- The lambda function calculates the sum of x and y, assigns it to the result, and prints “Sum: 12” to the console.
Lambda Capturing All Variables by Reference
#include
int main() {
int x = 5;
int y = 7;
auto myFun = [&] {
x++;
y++;
};
myFun();
std::cout << "x: " << x << ", y: " << y << std::endl;
return 0;
}
Output:
x: 6, y: 8
Explanation:
- The code initializes two integer variables, x, and y, with values 5 and 7.
- It defines a lambda function myFun using [&], which captures all variables in the current scope by reference, allowing the lambda to modify x and y.
- The lambda increments both x and y by 1 when called. After invoking myFun(), the program outputs “x: 6, y: 8” to the console.
Arrays
Arrays are collections of elements of the same data type, accessed by index positions. They provide a convenient way to work with multiple data elements under a single identifier.
Declaring and Initializing Arrays
To create an array in C++, you must declare its data type, name, and size. Here’s the basic syntax:
data_type array_name[array_size];
Here,
data_type: The type of data that the array will hold (e.g., int, float, char).
array_name: The identifier for the array.
array_size: The number of elements in the array.
You can also initialize arrays at the time of declaration. For example:
int numbers[5] = {1, 2, 3, 4, 5};
In the above example, we declare an integer array numbers with five elements and initialize them with specific values.
Accessing Array Elements
- Array elements are accessed using indices, starting from 0.
- For example, to access the first element of the numbers array, you would use numbers[0].
- To access the second element, you would use numbers[1], and so on.
- Example:
int firstElement = numbers[0]; // Accessing the first element
int secondElement = numbers[1]; // Accessing the second element
Example:
Here’s an example demonstrating the use of arrays.
// Simple Array
#include
using namespace std;
int main() {
// Declare an array to store integers
int arr[5] = {1, 2, 3, 4, 5};
// Display the elements of the array
std::cout << "Array elements:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << endl;
}
return 0;
}
Array elements:
1
2
3
4
5
Explanation:
- The code declares an integer array numbers with a size of 5 and initializes it with values from 1 to 5.
- It then uses a for loop to iterate through the array elements and prints them to the console, displaying “Array elements: 1 2 3 4 5” as the output.
Structures
- A structure is a composite data type that allows you to group together variables of different data types under a single name. This grouping makes it easier to manage related data and work with complex data structures.
- To define a structure, you use the struct keyword, followed by the structure’s name, and a pair of curly braces to enclose the member variables. The basic syntax of a structure looks like this:
struct StructureName {
data_type member1;
data_type member2;
// ...
data_type memberN;
};
Example: Here’s an example of a structure named “Person” with member variables for a person’s name, sex, and age:
#include
using namespace std;
// Define a structure named Person to store information about a person
struct Person
{
string name;
string sex;
int age;
};
int main()
{
// Create two instances of the Person structure, p1 and p2, to store information about two individuals
Person p1;
p1.name = "Prahelika";
p1.sex = "F";
p1.age = 22;
Person p2;
p2.name = "Tiana";
p2.sex = "F";
p2.age = 12;
// Display the information for the first person (p1)
cout << "Name: " << p1.name << endl;
cout << "Sex: " << p1.sex << endl;
cout << "Age: " << p1.age << endl;
cout << ".................................." << endl; // Separation line
// Display the information for the second person (p2)
cout << "Name: " << p2.name << endl;
cout << "Sex: " << p2.sex << endl;
cout << "Age: " << p2.age << endl;
return 0;
}
Name: Prahelika
Sex: F
Age: 22
Explanation:
- The code defines a structure called a Person with three members: name, sex, and age.
- It creates two instances of the Person structure, p1 and p2, and assigns values to their name, sex, and age members.
- The code then displays the information of both individuals, p1 and p2, including their names, genders, and ages, separated by a line of dots.
Object Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a transformative paradigm in the world of software development. Object-oriented programming (OOP) principles find a powerful and highly regarded implementation in the programming language C++, making it stand out for its robust object-oriented capabilities. Let’s delve deeper into the realm of OOP within the context of C++.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
What is OPP?
- OOP is a fundamental approach in C++ that facilitates the creation of software systems by modeling real-world entities using objects.
- Objects are instances of classes, which are user-defined data types. Classes define the structure and behavior of objects, encapsulating attributes (data members) and methods (functions). By using OOP, C++ promotes code modularity, reusability, and maintainability.
- OOP enables developers to break down complex systems into smaller, more manageable components, making it easier to design, develop, and maintain software.
- By creating classes that represent real-world entities and defining their interactions, C++ applications become more intuitive and maintainable. This approach aligns well with the structured, efficient, and maintainable software development principles, contributing to the overall success of C++ as a programming language.
Benefits of OPP
Modularity: OOP divides code into self-contained classes and objects, making it easier to manage and modify specific parts of the program without affecting the entire codebase.
Reusability: Classes and objects can be reused in different parts of a program or even in entirely separate projects, promoting code reusability.
Abstraction: OOP allows developers to abstract complex real-world entities into simplified, reusable models through classes, focusing on essential properties and behaviors.
Encapsulation: OOP encapsulates data within classes, providing control over data access and protection from unintended modifications.
Inheritance: It supports the creation of new classes by inheriting attributes and methods from existing classes, fostering code reuse and hierarchy.
Polymorphism: OOP enables objects of different classes to be treated as objects of a common base class, facilitating dynamic method invocation and adaptability.
Readability: By modeling code around real-world entities, OOP code tends to be more human-readable and easier to understand.
Maintenance: OOP promotes code maintainability, as changes or updates to one class typically have limited impacts on other parts of the program.
Efficiency: It can lead to more efficient code due to its structured and modular nature.
Community and Libraries: A vast community and extensive libraries support OOP languages like C++, providing access to pre-built classes and solutions.
Versatility: OOP is applicable to a wide range of applications, from desktop software to web development and game design.
What is the difference between OOP with Procedure-Oriented Programming (POP)?
Procedure-Oriented Programming (POP) relies on functions to organize code and lacks data abstraction, while OOP uses classes to encapsulate both data and methods for more structured and modular code. The difference between POP and OOP are presented in a tabular format to facilitate comprehension.
Aspect | Procedure-Oriented Programming (POP) | Object-Oriented Programming (OOP) |
---|---|---|
Paradigm | Focus on procedures/functions | Focus on objects and classes |
Data and Functionality | Data and functions are separate | Data and functions are encapsulated in classes |
Code Reusability | Limited reusability of functions | Extensive code reusability through inheritance |
Data Abstraction | Limited data abstraction, global data exposure | Strong data abstraction, controlled access |
Real-World Modeling | Inefficient for real-world modeling | Well-suited for real-world entity modeling |
Class
- A class in object-oriented programming (OOP) is a fundamental construct that defines the blueprint or template for creating objects.
- It is composed of various parts, each serving a specific role in organizing and modeling the behavior and structure of objects.
- Syntax of a Simple Class:
class ClassName {
public:
// Public attributes (variables)
DataType attributeName1;
DataType attributeName2;
// Public member functions (methods)
ReturnType methodName1(ParameterType parameter1, ParameterType parameter2) {
// Method implementation
}
ReturnType methodName2(ParameterType parameter) {
// Method implementation
}
};
Here’s a more detailed explanation of the various parts of a simple class as shown in the syntax above:
Class Name:
- In line number 1, a class is defined as class ClassName { … }.
- The class serves as a blueprint for creating objects, allowing you to define the structure and behavior of those objects.
- Everything related to the class, including attributes and methods, is enclosed within the curly braces.
Access Specifier:
- In line number 2, an access specifier defined as “public:“
- In this context, the public specifier is used to set the visibility of the class members declared beneath it. It makes these members accessible from outside the class.
- C++ offers three access specifiers: public, private, and protected, each with different visibility levels.
Attributes (Member Variables):
- In line number 4-5; attributes are defined as “DataType attributeName”.
- Attributes, also known as member variables, are used to store data within the class.
- You declare public attributes, where each attribute has a data type (e.g., int, string, float) and a unique name (e.g., attributeName1 and attributeName2).
- These attributes represent the data associated with objects created from the class.
Methods (Member Functions):
-
In line number 8-14, methods are defined as, “ReturnType methodName1 (ParameterType parameter1, ParameterType parameter2) { … }“
-
Methods are functions that are associated with the class and can perform operations on class attributes or provide specific functionalities.
-
They can have parameters and return values.
-
ReturnType: Specifies the data type of the value returned by the method. For methods that don’t return anything, you use void as the return type.
-
methodName1: The method’s name, which should be a valid C++ identifier.
-
(ParameterType parameter1, ParameterType parameter2): Parameters that the method accepts. Parameters are used to pass data into the method for processing.
Object
- An object is an instance of a class. It is a real entity created based on the class’s blueprint. You can think of objects as variables of the class type.
- Objects of a class can be created by specifying the class name followed by the object name, like ClassName ObjectName.
- Objects have access to the member variables and functions of their class. You can manipulate the data associated with an object and call its member functions.
- Syntax of a object:
ClassName objectName; // Creates an object of the class ClassName
Example:
Here is a code example that demonstrates the use of a class in C++.
// Simple Class
#include
using namespace std;
// Define a Student class
class Student
{
public:
string name;
int rollNumber;
float score;
// Member function to display student information
void displayInfo()
{
cout<<"Name: "<
Explanation
- The code defines a class named “Student“, which has three public attributes: “name“, “rollNumber“, and “score“.
- Two instances of the “Student” class, “obj1” and “obj2“, are created and initialized with specific values for their attributes.
- The “displayInfo” member function of the class is used to display the information of each student, including their name, rollNumber, and score.
Constructor
- A constructor in a C++ class is a special member function that is automatically called when an object of that class is created.
- Its main purpose is to set up the initial state of the object by initializing its attributes or performing other necessary setup tasks.
- Constructors are vital for ensuring that objects start with the expected initial values, maintaining a valid state from the moment they are created.
- Here’s an example of a constructor, focusing on the key elements
#include
class Rectangle {
public:
// Constructor with parameters
Rectangle(double length, double width) {
this->length = length;
this->width = width;
}
// Member function to calculate the area
double calculateArea() {
return length * width;
}
private:
double length;
double width;
};
int main() {
// Creating an object of the Rectangle class and invoking the constructor
Rectangle myRectangle(5.0, 3.0);
// Calculating and displaying the area
double area = myRectangle.calculateArea();
std::cout << "Area of the rectangle: " << area << std::endl;
return 0;
}
Output:
Area of the rectangle: 15
Explanation:
- We define a class called Rectangle with a constructor that accepts two parameters, length and width.
- When we create an object myRectangle of the Rectangle class in the main function, the constructor is automatically triggered with the values 5.0 and 3.0 for length and width.
- This initialization step ensures that the object is set up correctly.
- We utilize the calculateArea member function to compute and display the area of the rectangle.
Destructor
- A destructor is a special member function within a class that gets called automatically when an object of that class goes out of scope or is explicitly deleted.
- The primary purpose of a destructor is to release any resources or perform cleanup operations associated with the object, such as closing files, releasing memory, or other resource management tasks.
- Here’s an example to demonstrate the use of a destructor in a class
Example:
#include
class SimpleClass {
public:
SimpleClass() {
std::cout << "Constructor called" << std::endl;
}
~SimpleClass() {
std::cout << "Destructor called" << std::endl;
}
};
int main() {
SimpleClass obj1; // Creating an object of SimpleClass
SimpleClass obj2; // Creating another object of SimpleClass
return 0; // Both obj1 and obj2 go out of scope, their destructors are called here
}
Output:
Constructor called
Constructor called
Destructor called
Destructor called
Encapsulation
Encapsulation, a core principle of OOP, involves the bundling of an object’s attributes (data) and the methods (functions) that operate on that data into a single structure known as a class.
The primary objective of encapsulation is to shield the internal details of an object from external access while providing a controlled and well-defined interface for interactions.
The application of encapsulation in programming serves multiple vital purposes
- Data Hiding: Encapsulation allows you to mark certain data members of a class as private. This means that the data is hidden from external access, and only the methods within the class can modify or access it. This helps maintain the integrity and consistency of the data.
- Controlled Access: By defining public methods (getters and setters) for accessing and modifying private data members, you can control how external code interacts with an object. This control ensures that data is only accessed and manipulated in a predefined and safe manner.
- Code Organization: Encapsulation promotes a clean and organized code structure. Data and methods related to a particular entity are grouped within a class, making the code more modular and easier to understand and maintain.
- Flexibility: As the internal representation of an object is hidden from external code, it allows for changes to the implementation of a class without affecting code that uses the class. This concept is known as information hiding.
- Data Validation: Encapsulation enables the implementation of data validation rules within setter methods. This ensures that data remains consistent and within valid ranges.
- Security: Encapsulation enhances data security by preventing unauthorized access and modification. It reduces the likelihood of accidental data corruption.
Example: Here’s a simple example in C++ to illustrate encapsulation.
// Encapsulation Example
#include
using namespace std;
class Circle {
private:
float radius; // Private member variable
public:
// Public method to set the radius, encapsulating the private variable
void setRadius(float r) {
if (r > 0) {
radius = r; // Set the private radius
} else {
radius = 0; // Ensuring a valid value
}
}
// Public method to compute and return the area of the circle
float ComputeArea() {
float area = 3.1416 * radius * radius; // Use the private radius
return area;
}
};
int main() {
Circle obj1;
obj1.setRadius(10.5); // Set the radius using the public method
float Area = obj1.ComputeArea(); // Calculate the area
cout << "Area of the circle: " << Area << endl;
return 0;
}
Explanation
- The C++ code above demonstrates encapsulation using a class named Circle.
- Inside the Circle class, there’s a private data member, radius, hidden from direct access.
- Public member functions, setRadius and ComputeArea, provide controlled access to radius.
- The setRadius function validates the input and assigns a value to radius.
- Encapsulation ensures data security and allows interactions with the class to be controlled through designated functions.
A Real World Example of Encapsulation
Encapsulation is a fundamental concept in object-oriented programming (OOP), and it might seem complex at first. However, we can explain it in a simple way using a common everyday object—the TV remote control.
- Button Functions (Methods):A remote control has buttons for power, volume, and channels. These buttons are like methods or functions of an object. Just as you press the buttons to change settings without knowing their internal workings, you can call methods in a C++ class without understanding their implementation details.
- Battery Compartment (Attributes): Inside the remote, there’s a compartment for batteries. This compartment is like an attribute of an object, a place where the object stores data. You don’t need to understand the intricate wiring or electronics inside; you only need to know that it contains the batteries.
- No Interference: Your remote control works independently without interfering with the TV’s internal circuits. You can adjust the volume without worrying about TV channel settings. This separation of functionalities, where one part doesn’t interfere with the other, is similar to how objects in C++ maintain their internal state without impacting each other.
- User-Friendly: The TV remote control is designed to be user-friendly, allowing anyone to use it without needing an electrical engineering degree. In C++, encapsulation aims to provide a user-friendly way to work with objects, abstracting complex details and offering a straightforward interface.
- In C++, encapsulation serves the same purpose as your TV remote control. It bundles data (like button functions and the battery compartment) into an object, hiding the complexity of how those functions and data are managed internally. You use these objects without dealing with the nitty-gritty details, just like you use the remote to change channels without knowing how it communicates with the TV
Inheritance
Inheritance, a fundamental concept in C++ and object-oriented programming, empowers developers to create efficient, structured, and organized code. It allows for the creation of new classes that inherit attributes and behaviors from existing classes.
The Foundation: Parent and Child Classes
- Inheritance works by establishing a parent-child relationship between classes.
- At the core of this relationship, we have the parent class (also known as the base class or superclass) and the child class (derived class or subclass).
- The parent class acts as the blueprint, defining common attributes and behaviors shared by all derived classes.
Basic Inheritance
Inheritance is about creating parent-child relationships between classes. Let us explain various parts of inheritance in a stepwise manner.
Step 1: Create A Base Class
- In the first step, we define the base class, which will serve as the foundation for our inheritance hierarchy. Here the base class is named as animal.
- We use the class keyword to declare the class. It’s where we define attributes and behaviors common to all animals, such as the eat and sleep functions.
- The public access specifier indicates that the eat and sleep functions from this base class can be accessible to derived classes (child classes).
// Step 1: Create a Base Class
#include
using namespace std;
class animal {
public:
void eat() {
cout << "We eat to live" << endl;
}
void sleep() {
cout << "We sleep at night" << endl;
}
};
Step 2: Create A Child Class
- Define the child class using the class keyword.
- Use the colon (:) followed by the access specifier (public, protected, or private) and the base class name to specify inheritance.
- Add data members and member functions specific to the child class.
// Step 2: Create a Child Class Inheriting from the Base Class
class Dog : public animal {
public:
void introduce() {
cout << "We are dogs, and we are domestic animals" << endl;
}
void bark() {
cout << "We are good at barking" << endl;
}
};
Step 3: Call Base Class and Child Class in Main Function
- In the main function, create objects of both the base class and the child class.
- Use these objects to call the member functions of the base class and the child class.
// Call Base Class and Child Class in the main Function
int main() {
cout << "DETAILS OF GENERAL ANIMALS" << endl;
cout << ".............................." << endl;
animal animal_obj1;
animal_obj1.eat();
animal_obj1.sleep();
cout << endl;
cout << "DETAILS OF DOGS" << endl;
cout << ".............................." << endl;
Dog dog_object1;
dog_object1.introduce();
dog_object1.eat();
dog_object1.sleep();
dog_object1.bark();
return 0;
}
Access control
Access control in inheritance refers to the control over the visibility and accessibility of base class members (e.g., variables and functions) in a derived class. There are three access specifiers that determine how the members of a base class can be accessed in a derived class.
Public Inheritance
- When you inherit a base class publicly, all the public members of the base class become public members of the derived class, and all protected members of the base class become protected members of the derived class.
- Private members of the base class remain inaccessible in the derived class.
- For example :
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
class Derived : public Base {
// publicMember remains public in Derived.
// protectedMember remains protected in Derived.
// privateMember is not accessible in Derived.
};
Example: Here are simple code example to illustrate public inheritance.
#include
class Base {
public:
void publicFunction() {
std::cout << "Public function in the Base class." << std::endl;
}
};
class Derived : public Base {
};
int main() {
Derived derivedObject;
derivedObject.publicFunction(); // Accessing the public function of the Base class
return 0;
}
Output:
Public function in the Base class
Explanation:
- The code showcases public inheritance.
- There are two classes: “Base” and “Derived“.
- The “Base” class contains a public member function called “publicFunction“.
- The “Derived” class inherits publicly from the “Base” class.
- In the “main” function, an instance of the “Derived” class, “derivedObject,” is created.
- “derivedObject.publicFunction()” successfully accesses and executes the public function from the “Base” class.
Protected Inheritance
- When you inherit a base class protectedly, all public and protected members of the base class become protected members of the derived class.
- Private members of the base class remain inaccessible in the derived class.
- For example:
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
class Derived : protected Base {
// publicMember becomes protected in Derived.
// protectedMember remains protected in Derived.
// privateMember is not accessible in Derived.
};
Example: Here are simple code examples to illustrate protected inheritance.
// Protected Inheritance
#include
class Base {
public:
void publicFunction() {
std::cout << "Public function in the Base class." << std::endl;
}
};
class Derived : protected Base {
};
int main() {
Derived derivedObject;
derivedObject.publicFunction(); // This line would result in a compilation error
return 0;
}
Explanation:
- The above code demonstrates protected inheritance.
- The “Base” class has a public member function, “publicFunction“.
- The “Derived” class inherits from the “Base” class with protected inheritance, making “publicFunction” protected within the “Derived” class.
- Attempting to access “publicFunction” directly from an instance of the “Derived” class results in a compilation error, highlighting the impact of protected inheritance on member accessibility.
However, we can access the base class members while implementing protected inheritance, by creating public member functions in the derived class that provide access to the protected members of the base class. Here’s a modified version of the code that demonstrates this:
#include
class Base {
public:
void publicFunction() {
std::cout << "Public function in the Base class." << std::endl;
}
};
class Derived : protected Base {
public:
void accessBasePublicFunction() {
publicFunction(); // Access the publicFunction from the base class
}
};
int main() {
Derived derivedObject;
derivedObject.accessBasePublicFunction(); // Accessing the publicFunction from the base class using a public member function
return 0;
}
OutputL:
Public function in the Base class
Explanation:
The code features a “Base” class with a public member function called “publicFunction,” which prints a message to the console when called. This function is accessible to any derived class or external code.
The “Derived” class inherits from the “Base” class using protected inheritance. As a result, the “publicFunction” becomes a protected member within the “Derived” class, restricting direct external access.
To access the inherited “publicFunction” from the “Base” class within the “Derived” class, a new public member function called “accessBasePublicFunction” is introduced in the “Derived” class. This function acts as a bridge, allowing the “Derived” class to call and utilize the protected “publicFunction” from the base class, even though it’s protected within the inheritance hierarchy.
Private Inheritance
- When a class privately inherits from a base class, the public and protected members of the base class become private members in the derived class.
- Private members are not accessible outside the class in which they are defined. This means that the base class’s public and protected members essentially become private in the derived class.
- Derived classes can still use these private inherited members within their own class, but they are hidden from the outside world.
- Private inheritance is often used when you want to encapsulate or hide the implementation details of the base class, restricting access to the base class’s interface.
- For example:
class Base {
public:
int publicMember; // Public member
protected:
int protectedMember; // Protected member
private:
int privateMember; // Private member
};
class Derived : private Base {
// publicMember and protectedMember become private in Derived.
// privateMember remains private in Derived.
// They are not directly accessible outside of Derived.
};
Example: Here are simple code examples to illustrate private inheritance.
#include
class Base {
private:
void privateMethod() {
std::cout << "This is a private method in the Base class." << std::endl;
}
};
class Derived : private Base {
};
int main() {
Derived derivedObject;
derivedObject.privateMethod(); // This line will result in a compilation error
return 0;
}
Explanation:
- The code above demonstrates private inheritance, where the Derived class inherits privately from the Base class.
- It attempts to call a private method named privateMethod of the Base class using an object of the Derived class in the main function.
- However, a private inheritance prevents direct access to base class private members from the derived class, resulting in a compilation error when trying to call privateMethod.
Example:
Let us modify the above code to allow the derived class to access the private method of the base class. Here’s a modified example:
#include
class Base {
private:
void privateMethod() {
std::cout << "Private method in Base class." << std::endl;
}
public:
void accessPrivateMethod() {
privateMethod(); // Access the private method through a public method
}
};
class Derived : private Base {
public:
void callBasePrivateMethod() {
accessPrivateMethod(); // Access the base class's private method indirectly
}
};
int main() {
Derived derived;
derived.callBasePrivateMethod(); // Calls the base class's private method through the derived class
return 0;
}
Explanation:
- The code defines two classes, Base and Derived. Base has a private method, privateMethod, and a public method, accessPrivateMethod, which indirectly accesses the private method.
- Derived is derived from Base using private inheritance, making the privateMethod private in the derived class, so it can’t be accessed directly.
- In the main function, an object of Derived calls the callBasePrivateMethod, which indirectly invokes the private method using the public method.
Dr. Partha Majumder is a distinguished researcher specializing in deep learning, artificial intelligence, and AI-driven groundwater modeling. With a prolific track record, his work has been featured in numerous prestigious international journals and conferences. Detailed information about his research can be found on his ResearchGate profile. In addition to his academic achievements, Dr. Majumder is the founder of Paravision Lab, a pioneering startup at the forefront of AI innovation.
Asking questions are genuinely nice thing if you are not understanding
anything entirely, however this paragraph offers good understanding even.
When someone writes an piece of writing he/she retains the image of
a user in his/her mind that how a user can understand it. Thus that’s why this post is outstdanding.
Thanks!
As the admin of thi website is working, no hesitation vsry soon it will bee renowned,
due to its feature contents. https://WWW.Waste-ndc.pro/community/profile/tressa79906983/
As thhe admin of this website is working, no hesitation very soon it
will be renowned, due to its feature contents. https://WWW.Waste-ndc.pro/community/profile/tressa79906983/
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.