Unit I Introduction toC++
Unit I Introduction toC++
Type modifiers in C++ also let you change how a data type behaves. A variable’s initial
value cannot be altered once it has been initialised, according to the const modifier.
With integer types, the signed and unsigned modifiers are used to determine whether or
not the values can be negative. Here’s an illustration of how to use type modifiers:
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
B. Formatting Output:
C++ provides several ways to format output using the cout object.
–setw() function to specify the width of the output.
–setprecision() function to specify the number of decimal places to display for floating-
point numbers.
–setfill() function to specify the fill character for the output.
Here’s an example of using formatting functions:
double pi = 3.14159265358979323846;
cout << "Pi is approximately: " << setprecision(4) << pi << endl;
C. String Manipulation:
C++ provides several functions for manipulating strings, which are represented by the
string class.
– “+” operator to concatenate strings
– size() function to get the length of a string
– substr() function to get a substring of a string
Here’s an example of using string manipulation functions:
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << "Full name: " << fullName << endl;
cout << "Length of full name: " << fullName.size() << endl;
cout << "First name: " << fullName.substr(0, 4) << endl;
// Output
Full name: John Doe
Length of full name: 8
First name: John
int day = 1;
switch (day) {
case 1:cout << "Monday" << endl; break;
case 2:cout << "Tuesday" << endl; break;
// ...
default:cout << "Invalid day" << endl;
}
B. Looping Statements:
C++ provides several looping statements like for, while, and do-while to execute a block
of code repeatedly.
– “for” loop executes a block of code a fixed number of times
– “while” the while loop executes a block of code as long as a specified condition is true
– “do-while” loop is similar to the while loop, but it always executes the block of code at
least once
Here’s an example of using looping statements:
int j = 0;
while (j < 10) {
cout << j << endl;
j++;
}
int k = 0;
do {
cout << k << endl;
k++;
} while (k < 10);
C. Nested Loops and Conditional Statements:
You can also nest conditional statements and loops to create more complex control flow
structures. Here’s an example of using nested loops and conditional statements:
int myArray[5];
int myArray[5] = {1, 2, 3, 4, 5}; //array of size 5
To access elements we need to use the index
int myArray[3][4];
int myArray[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
To access the elements we use:
int x = myArray[0][1]; // access the element in the first row and second column
C. Introduction to Pointers:
A pointer is a variable that holds the memory address of another variable. Pointers are
often used in C++ for dynamic memory allocation and for passing parameters by
reference.
int* myPointer;
int x = 10;
myPointer = &x; //This declares a pointer variable that can hold the memory
address of an integer variable.
D. Pointers and Arrays:
In C++, arrays and pointers are closely related. In fact, the name of an array is a pointer
to the first element in the array.
To declare a pointer to an array, you can use the following syntax:
int myArray[5];
int* myPointer = myArray;
This creates a pointer variable myPointer that points to the first element in the array
myArray. You can access individual elements in the array using pointer arithmetic:
#include <iostream.h>
using namespace std;
int main() {
int n = 10, t1 = 0, t2 = 1, nextTerm;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i) {
cout << t1 << " + ";
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
Object Oriented Programming Class
1.Class
The building block of C++ that leads to Object-Oriented programming is a Class. It is a
user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object. For Example: Consider the Class of Cars. There may be many
cars with different names and brands but all of them will share some common properties
like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is
the class, and wheels, speed limits, and mileage are their properties.
A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables together these data members and member functions define
the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage, etc
and member functions can apply brakes, increase speed, etc.
We can say that a Class in C++ is a blueprint representing a group of objects which
shares some common properties and behaviors.
2.Object
An Object is an identifiable entity with some characteristics and behavior. An Object is
an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
C++
// C++ Program to show the syntax/working of Objects as a
// part of Object Oriented PProgramming
#include <iostream.h>
using namespace std;
class person {
char name[20];
int id;
public:
void getdetails() {}
};
int main()
{
Class Object
The class has to be declared first An object is created many times as per
and only once. requirement.
3.Data Abstraction:
Data Abstraction in C++ means providing only the essential details to the outside world
and hiding the internal details, i.e., hiding the background details or implementation.
Abstraction is a programming technique that depends on the separation of the interface
and implementation details of the program.
Ways to implement Data Abstraction in C++
Abstraction using classes
Abstraction in C++ programming language can be implemented in classes. The class
helps the programmers to group the members of that data and function by using
available access specifiers. A class is the main deciding factor of which data member
will be visible to the world or which is not.
Abstraction using header files
Another type of abstraction in the C++ programming language is related to header files.
For instance, let's consider the pow() method present in the math.h header file. If the
developer needs to calculate the power of a number, then it is called the function pow()
which is present in the math.
Example
C++ Tokens
C++ Tokens are the tiniest individual units of any program. C++ is the superset of ‘C’ and
so most constructs of ‘C’ are permissible in the ‘C++’ with their sense and usage
unaffected. So tokens, expressions, and the data types are equal to that of ‘C’.C++
Tokens are the tiniest individual units of any program. C++ is the superset of ‘C’ and so
most constructs of ‘C’ are permissible in the ‘C++’ with their sense and usage unaffected.
So tokens, expressions, and the data types are equal to that of ‘C’.
Following, given below are the ‘C++’ tokens: (most of the ‘c++’ tokens are basically equal
to the ‘C’ tokens, respectively)
• Keywords
• Identifiers
• Constants
• Variables
• Operators
Keywords
These are the reserved words that have a fixed and definite meaning, and their sense
cannot be changed or modified. Moreover, the meaning and the working process of these
keywords are already known to the compiler. ‘C++’ has more numbers of keywords as
compared to ‘C’, and those extra ones are having special working abilities.
There are a total of 32 of these, and these are as follows:
auto const double float int short struct unsigned
break continue elseforlong signed switch void
case default enumgoto register sizeof typedef volatile
char do extern if return static unionwhile
There are additional 30 reserved words that were not in ‘C’, these are therefore new
to the ‘C++’, and these are as follows:
asm dynamic_cast namespace reinterpret_cast try
bool explicit new static_cast typeid
catch false operator template typename
class friend privatethis using
const_cast inline public throw virtual
delete mutable protected true wchar_t
Browse more Topics Under Getting Started with C++
• C++ Character Set
• Structure of a C++ Program
• Header Files
• Use of I/O Operators
• Use of endl and setw
• Cascading of I/O Operators
• Compilation in C++
• Error Messages
• Use of Editor
• Basic Commands of Editor
• Linking in C++
• Execution in C++
Identifiers
Identifiers are the names that are given to the different entries just like variables,
structures, as well as functions. Also, the names of the identifiers should be unique
because these entities are applicable to the implementation of the program.
Identifier naming conventions
Only the alphabetic characters, digits, and underscores are allowed.
The first letter should be an alphabet or an underscore (_).
The identifiers are case-sensitive.
Keywords that are reserved can’t be used as the name of the identifier.
Constants
Constants are similar to a variable, except for one thing, that is their value which never
changes during the execution process once defined.
There are two more different ways of defining the constants in ‘C++’. These are as
follows:
By the use of the ‘const’ keyword
By the use of the ‘#define’ pre-processor
Declaration of a constant:
const [data_type] [constant_name]=[value];
Variable
A variable is a name that is meaningful. In addition, this name is basically of the data
storage location in a computer system’s memory. Similarly, when we use a variable we
refer to the memory address of the computer system.
Syntax to declare a variable
[data_type] [variable_name];
Example
#include
int main() {
cin>>a;
cin>>b;
int sum;
sum=a+b;
Example:
#include <iostream.h>
int main() {
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
cout << sum1 << "\n";
cout << sum2 << "\n";
cout << sum3;
return 0;
}
• Assignment operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10
to a variable called x:
Example
int x = 10;
The addition assignment operator (+=) adds a value to a variable:
Example
int x = 10;
x += 5;
A list of all assignment operators:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
FAQ on C++ Tokens
Comparison operators
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important
in programming, because it helps us to find answers and make decisions.
The return value of a comparison is either 1 or 0, which means true (1) or false (0).
These values are known as Boolean values, and you will learn more about them in
the Booleans and If..Else chapter.
In the following example, we use the greater than operator (>) to find out if 5 is greater
than 3:
A list of all comparison operators:
In C++, comparison operators are used to compare two values or expressions. They
yield a boolean result (true or false) based on the outcome of the comparison. Here are
the primary comparison operators available in C++:
1. Equal to (==):
o Syntax: a == b
o Checks if a is equal to b.
o Example: if (x == 10) { /* ... */ }
2. Not equal to (!=):
o Syntax: a != b
o Checks if a is not equal to b.
o Example: if (x != 10) { /* ... */ }
3. Greater than (>):
o Syntax: a > b
o Checks if a is greater than b.
o Example: if (x > 10) { /* ... */ }
4. Less than (<):
o Syntax: a < b
o Checks if a is less than b.
o Example: if (x < 10) { /* ... */ }
5. Greater than or equal to (>=):
o Syntax: a >= b
o Checks if a is greater than or equal to b.
o Example: if (x >= 10) { /* ... */ }
6. Less than or equal to (<=):
o Syntax: a <= b
o Checks if a is less than or equal to b.
o Example: if (x <= 10) { /* ... */ }
#include <iostream.h>
int main() {
int a = 10, b = 20;
if (a == b) {
cout << "a is equal to b" << endl;
} else if (a != b) {
cout << "a is not equal to b" << endl;
}
if (a < b) {
cout << "a is less than b" << endl;
}
if (a > b) {
cout << "a is greater than b" << endl;
}
if (a <= b) {
cout << "a is less than or equal to b" << endl;
}
if (a >= b) {
cout << "a is greater than or equal to b" << endl;
}
return 0;
}
Logical operators in C++ are used to perform logical operations on boolean values.
Here are the key logical operators:
1. Logical AND (&&):
o Syntax: expr1 && expr2
o Returns true if both expr1 and expr2 are true; otherwise, returns false.
o Example: if (x > 0 && y > 0) { /* ... */ }
2. Logical OR (||):
o Syntax: expr1 || expr2
o Returns true if either expr1 or expr2 is true; otherwise, returns false.
o Example: if (x > 0 || y > 0) { /* ... */ }
3. Logical NOT (!):
o Syntax: !expr
o Returns true if expr is false; otherwise, returns false.
o Example: if (!(x > 0)) { /* ... */ }
Examples:
#include <iostream.h>
int main() {
bool a = true, b = false;
// Logical AND
if (a && b) {
cout << "Both a and b are true" << endl;
} else {
cout << "At least one of a or b is false" << endl;
}
// Logical OR
if (a || b) {
cout << "At least one of a or b is true" << endl;
}
// Logical NOT
if (!b) {
cout << "b is false" << endl;
}
return 0;
}
Key Points:
• Logical operators are often used in conditional statements and loops to combine
or invert boolean conditions.
• They perform short-circuit evaluation: in &&, if the first expression is false, the
second expression is not evaluated; in ||, if the first expression is true, the second
expression is not evaluated.
Bitwise operators
itwise operators in C++ operate on the binary representations of integers. They perform
operations on the individual bits of the values. Here's a rundown of the main bitwise
operators:
1. Bitwise AND (&):
o Syntax: a & b
o Performs a bitwise AND operation between each bit of a and b. The result
has a bit set to 1 if both corresponding bits of a and b are 1.
o Example: 0101 & 0011 = 0001
2. Bitwise OR (|):
o Syntax: a | b
o Performs a bitwise OR operation between each bit of a and b. The result
has a bit set to 1 if at least one of the corresponding bits of a or b is 1.
o Example: 0101 | 0011 = 0111
3. Bitwise XOR (^):
o Syntax: a ^ b
o Performs a bitwise XOR (exclusive OR) operation between each bit of a
and b. The result has a bit set to 1 if exactly one of the corresponding bits
of a or b is 1.
o Example: 0101 ^ 0011 = 0110
4. Bitwise NOT (~):
o Syntax: ~a
o Performs a bitwise NOT operation on a. It inverts all the bits in a, turning
0s into 1s and 1s into 0s.
o Example: ~0101 = 1010 (for a 4-bit number)
5. Bitwise Shift Left (<<):
o Syntax: a << n
o Shifts the bits of a to the left by n positions. Zeroes are shifted into the
vacated positions on the right.
o Example: 0001 << 2 = 0100
6. Bitwise Shift Right (>>):
o Syntax: a >> n
o Shifts the bits of a to the right by n positions. The vacated positions on the
left are filled with zeros for unsigned types, or with the sign bit for signed
types (arithmetic shift).
o Example: 0100 >> 2 = 0001
Examples:
#include <iostream.h>
int main() {
unsigned int a = 5; // Binary: 0101
unsigned int b = 3; // Binary: 0011
cout << "a & b: " << (a & b) << endl; // Binary: 0001, Decimal: 1
cout << "a | b: " << (a | b) << endl; // Binary: 0111, Decimal: 7
cout << "a ^ b: " << (a ^ b) << endl; // Binary: 0110, Decimal: 6
cout << "~a: " << (~a) << endl; // Binary: ...1111010 (depending on integer size)
cout << "a << 1: " << (a << 1) << endl; // Binary: 1010, Decimal: 10
cout << "a >> 1: " << (a >> 1) << endl; // Binary: 0010, Decimal: 2
return 0;
}
Key Points:
• Bitwise AND: Useful for masking specific bits.
• Bitwise OR: Useful for setting specific bits.
• Bitwise XOR: Useful for toggling specific bits.
• Bitwise NOT: Useful for inverting all bits.
• Bitwise Shift Left/Right: Useful for multiplying or dividing by powers of two, or
for bit manipulation tasks.
These operators are particularly useful in low-level programming, such as system
programming, embedded systems, and performance-critical applications where direct
bit manipulation is necessary.
Expression and control structure
In C++, expressions and control statements are fundamental constructs that dictate the
flow and behavior of a program.
Expressions
An expression in C++ is a combination of variables, constants, operators, and functions
that evaluates to a value. Expressions can be simple or complex:
1. Arithmetic Expressions:
o Perform mathematical operations.
o Example: a + b, x * y / 2
2. Relational Expressions:
o Compare values and return boolean results.
o Example: a > b, x == 10
3. Logical Expressions:
o Use logical operators to combine boolean values.
o Example: (a > b) && (x < y)
4. Assignment Expressions:
o Assign a value to a variable.
o Example: x = 5, a += 10
Control Statements
Control statements manage the flow of execution in a program. They include:
1. Conditional Statements:
o if:
▪ Executes a block of code if a condition is true.
▪ Example:
if (x > 0) {
// Code to execute if x is greater than 0
}
o if-else:
▪ Executes one block of code if the condition is true, and another
block if false.
▪ Example:
if (x > 0) {
// Code for true condition
} else {
// Code for false condition
}
o else if:
▪ Provides additional conditions to test if the previous conditions are
false.
▪ Example:
if (x > 0) {
// Code for x > 0
} else if (x == 0) {
// Code for x == 0
} else {
// Code for x < 0
}
2. Switch Statement:
o Chooses among multiple options based on the value of a variable.
o Example:
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
// More cases...
default: cout << "Invalid day"; break;
}
3. Loops:
o for:
▪ Repeats a block of code a specific number of times.
▪ Example:
do {
// Code to execute
++x;
} while (x < 10);
4. Jump Statements:
o break:
▪ Exits the current loop or switch statement.
▪ Example: Used inside loops or switch cases to exit early.
o continue:
▪ Skips the rest of the current loop iteration and proceeds to the next
iteration.
▪ Example: Used to skip certain iterations in a loop.
o return:
▪ Exits a function and optionally returns a value.
▪ Example: return 0; exits the function and returns 0.
Examples:
#include <iostream.h>
int main() {
int x = 5;
// Conditional Statement
if (x > 0) {
cout << "x is positive" << endl;
} else {
cout << "x is not positive" << endl;
}
// Switch Statement
int day = 3;
switch (day) {
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
case 3: cout << "Wednesday"; break;
default: cout << "Invalid day"; break;
}
cout << endl;
// Loop
for (int i = 0; i < 5; ++i) {
cout << "i = " << i << endl;
}
return 0;
}
Key Points:
• Expressions evaluate to values and can be used anywhere in the code.
• Control statements alter the flow of execution based on conditions or loops.
Symbolic Constants
In C++, symbolic constants are named constants whose values are set at compile-time
and cannot be changed during program execution. They enhance code readability and
maintainability by giving meaningful names to constant values. Here’s how you can
define and use symbolic constants:
Defining Symbolic Constants
1. Using const Keyword:
o Syntax: const type name = value;
o Example:
// Using const
const int MAX_USERS = 100;
constexpr double PI = 3.14159;
// Using enum
enum class Status { OK, ERROR, UNKNOWN };
int main() {
cout << "Max users: " << MAX_USERS << endl;
cout << "Value of PI: " << PI << endl;
return 0;
}
Key Points:
• const and constexpr are type-safe and scoped within their declaration.
• enum and enum class are used for groups of related constants, with enum
class providing better type safety and scoping.
• #define is a preprocessor directive and lacks type safety and scope control
compared to the other methods.
Type Compatability
type compatibility in C++ refers to how types interact with each other in expressions and
assignments. Understanding type compatibility is crucial for writing correct and efficient
C++ code. Here’s a brief overview:
1. Implicit Type Conversion (Type Promotion)
C++ performs automatic type conversion when types in an expression are mixed. This
is known as type promotion or implicit conversion.
• Numeric Promotion: Smaller integer types (char, short) are promoted to int.
Floating-point types (float) are promoted to double.
int a = 5;
double b = 2.5;
double result = a + b; // 'a' is promoted to double
• Integer Promotion: If an int is involved in operations with a long, the int is
promoted to long.
2. Type Casting
Explicit conversion between types can be performed using type casting.
• static_cast: Used for safe, compile-time checks for conversions.
double pi = 3.14;
int intPi = static_cast<int>(pi); // Converts double to int
• dynamic_cast: Used for safely downcasting in polymorphic class hierarchies
(requires RTTI).
Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // Safe downcasting
• const_cast: Used to add or remove const from a variable.
const int x = 10;
int& y = const_cast<int&>(x); // Removes const-ness
• reinterpret_cast: Used for low-level casting, often between unrelated types.
int* p = reinterpret_cast<int*>(0x12345678); // Treats the address as an int
pointer
3. Type Compatibility Rules
• Assignment Compatibility: When assigning one type to another, the compiler
checks if the source type can be converted to the destination type. For example,
double can be assigned to int with implicit conversion (but it may lose data).
int a = 10;
double b = a; // Implicit conversion from int to double
• Function Overloading: Functions can be overloaded based on different
parameter types. The best match is selected based on type compatibility.
void print(int x);
void print(double x);
• Type Compatibility in Templates: C++ templates need to handle type
compatibility, template <typename T>
void func(T a) {
// Function implementation
}
Examples:
#include <iostream.h>
int main() {
int i = 10;
double d = 5.5;
double result = i + d; // 'i' is promoted to double
// Static cast
int intResult = static_cast<int>(result);
return 0;
}
Key Points:
• Implicit Conversions: Automatic conversions based on type promotion rules.
• Explicit Casts: Controlled type conversion using static_cast, dynamic_cast,
const_cast, and reinterpret_cast.
• Type Compatibility Rules: Ensure operations and assignments between types
are valid according to C++ rules.
Understanding these concepts helps prevent type-related errors and ensures that type
conversions
Variables
In C++, variables are named storage locations used to hold data that can be modified
and accessed throughout the program. Here’s a concise overview of variables in C++:
1. Declaration and Initialization
• Declaration: Specifies the type and name of the variable.
int age; // Declares an integer variable named age
• Initialization: Assigns a value to a variable at the time of declaration.
int age = 25; // Declares and initializes the variable age
2. Variable Types
• Basic Data Types:
o int - Integer type.
o float - Single-precision floating-point.
o double - Double-precision floating-point.
o char - Single character.
o bool - Boolean (true or false).
• Derived Data Types:
o Arrays: Collection of elements of the same type.
int numbers[5]; // Array of 5 integers
o Pointers: Variables that hold memory addresses.
int* ptr; // Pointer to an integer
o References: Alias for another variable.
int value = 10;
int& ref = value; // Reference to value
o Structures: User-defined types that group variables.
struct Person {
string name;
int age;
};
union Data {
int intValue;
float floatValue;
};
o Enumerations: Defines a set of named integral constants.
enum Color { RED, GREEN, BLUE };
3. Scope and Lifetime
• Local Variables: Declared inside a function or block; accessible only within that
scope.
void func() {
int localVar = 10; // Local variable
}
• Global Variables: Declared outside all functions; accessible throughout the
program.
int globalVar = 20; // Global variable
• Static Variables: Retain their value between function calls.
void func() {
static int count = 0; // Static variable
count++;
}
• Dynamic Variables: Allocated at runtime using new and deallocated with delete.
int* p = new int; // Dynamically allocated integer
delete p; // Deallocate memory
Examples:
#include <iostream.h>
#include <string>
struct Person {
string name;
int age;
};
int main() {
// Local Variable
int localVar = 10;
// Array
int numbers[3] = {1, 2, 3};
// Pointer
int* ptr = &localVar;
// Reference
int& ref = localVar;
// Static Variable
static int staticVar = 0;
staticVar++;
// Dynamic Variable
int* dynamicVar = new int(50);
Person person;
person.name = "Alice";
person.age = 30;
void func() {
int value = 20; // Local variable
cout << "Local value: " << value << endl;
cout << "Global value: " << ::value << endl; // Access global variable
}
int main() {
func();
return 0;
}
2. Accessing Namespace Members
Namespaces help organize code into logical groups and prevent name conflicts. The
scope resolution operator is used to access members of a namespace.
#include <iostream.h>
namespace MyNamespace {
int value = 42;
}
int main() {
cout << "Namespace value: " << MyNamespace::value << endl; // Access
namespace member
return 0;
}
3. Defining Class Members Outside the Class
When defining a member function of a class outside the class definition, the scope
resolution operator is used to specify which class the function belongs to.
#include <iostream.h>
class MyClass {
public:
void display();
};
int main() {
MyClass obj;
obj.display(); // Call member function
return 0;
}
4. Accessing Base Class Members
In derived classes, the scope resolution operator can be used to access members of the
base class that might be hidden by derived class members.
#include <iostream.h>
class Base {
public:
void show() { cout << "Base show()" << endl; }
};
int main() {
Derived obj;
obj.show(); // Calls Derived's show()
obj.showBase(); // Calls Base's show()
return 0;
}
5. Using :: for Member Function Templates
When dealing with class templates, the scope resolution operator is used to define
member functions outside the class template definition.
#include <iostream.h>
int main() {
MyClass<int> obj;
obj.display(); // Calls the template member function
return 0;
}
Key Points:
• Global Scope Access: Use :: to access global variables or functions when their
names are hidden by local variables.
• Namespace Scope: Use :: to access elements within a namespace.
• Class Member Definitions: Use :: to define member functions outside the class
definition.
• Base Class Access: Use :: to access base class members in derived classes.
• Template Member Functions: Use :: to define member functions of class
templates outside the class definition.
The scope resolution operator helps manage the visibility of identifiers and resolve
ambiguities in C++ programs, ensuring that the correct variables, functions, or class
members are accessed as intended.
Member Referencing Operators
class Person {
public:
string name;
int age;
};
int main() {
Person person;
person.name = "Alice"; // Using dot operator to access member
person.age = 30;
cout << "Name: " << person.name << ", Age: " << person.age << endl;
return 0;
}
2. Arrow Operator (->)
Used to access members of an object through a pointer to that object.
• Syntax: pointer->member
• Example:
#include <iostream.h>
class Person {
public:
string name;
int age;
};
int main() {
Person person;
Person* ptr = &person;
ptr->name = "Bob"; // Using arrow operator to access member
ptr->age = 25;
cout << "Name: " << ptr->name << ", Age: " << ptr->age << endl;
return 0;
}
3. Pointer-to-Member Operator (.*)
Used to access a member of an object through a pointer to a member, often in
conjunction with a pointer to an object.
• Syntax: object.*memberPointer
• Example:
#include <iostream.h>
class Person {
public:
string name;
int age;
};
int main() {
Person person;
person.name = "Charlie";
person.age = 40;
cout << "Name: " << person.*ptrToName << endl; // Accessing member
through pointer-to-member
cout << "Age: " << person.*ptrToAge << endl;
return 0;
}
4. Pointer-to-Member Function Operator (->*)
Used to call a member function on an object through a pointer to that member function.
• Syntax: object->*memberFunctionPointer()
• Example:
#include <iostream.h>
class Person {
public:
void greet() const {
cout << "Hello!" << endl;
}
};
int main() {
Person person;
void (Person::*ptrToGreet)() const = &Person::greet;
int main() {
int* p = new int; // Allocate memory for a single integer
*p = 10;
cout << "Value: " << *p << endl;
delete p; // Deallocate memory
return 0;
}
2. delete Operator
Deallocates memory previously allocated with new. It should be used for single object
deallocation.
• Syntax:
delete pointer;
• Example:
int* p = new int;
delete p; // Correct usage
3. delete[] Operator
Deallocates memory previously allocated with new[]. It is used for arrays.
• Syntax:
delete[] arrayPointer;
• Example:
int* arr = new int[5];
delete[] arr; // Correct usage for arrays
4. new and delete with Class Objects
When working with class objects, new and delete operate similarly, allocating and
deallocating memory for objects.
• Example:
class MyClass {
public:
MyClass() { cout << "Constructor called" << endl; }
~MyClass() { cout << "Destructor called" << endl; }
};
int main() {
MyClass* obj = new MyClass; // Allocate memory for MyClass object
delete obj; // Deallocate memory
return 0;
}
Key Points:
• new: Allocates memory and returns a pointer to the allocated memory.
• delete: Deallocates memory for a single object allocated with new.
• new[]: Allocates memory for an array of objects and returns a pointer to the first
element.
• delete[]: Deallocates memory for an array of objects allocated with new[].
Proper use of these operators ensures efficient memory management and helps avoid
memory leaks and dangling pointers.
Manipulators
In C++, manipulators are used to format the output and control the behavior of the
input/output streams. They are part of the I/O library (<iostream.h>) and help in
adjusting the appearance of output, such as setting the width, precision, and format of
data.
Commonly Used I/O Manipulators
1. endl
• Function: Inserts a newline character into the output stream and flushes the
stream.
• Syntax: cout << endl;
• Example:
#include <iostream.h>
int main() {
cout << "Hello, World!" << endl;
return 0;}
2. setw
• Function: Sets the width of the next input/output field.
• Syntax: setw(width)
• Example:
#include <iostream.h>
#include <iomanip> // For setw
int main() {
cout << setw(10) << 42 << endl; // Right-aligned by default
return 0;
}
3. setfill
• Function: Sets the fill character used when outputting fields with setw.
• Syntax: setfill(char)
• Example:
#include <iostream.h>
#include <iomanip> // For setfill
int main() {
cout << setw(10) << setfill('*') << 42 << endl;
return 0;
}
4. setprecision
• Function: Sets the number of digits to be displayed after the decimal point for
floating-point numbers.
• Syntax: setprecision(precision)
• Example:
#include <iostream.h>
#include <iomanip> // For setprecision
int main() {
double pi = 3.141592653589793;
cout << fixed << setprecision(2) << pi << endl;
return 0;
}
5. fixed and scientific
• Function: Controls the format of floating-point numbers. fixed shows numbers in
fixed-point notation, and scientific shows them in scientific notation.
• Syntax: fixed, scientific
• Example:
#include <iostream.h>
#include <iomanip> // For fixed and scientific
int main() {
double number = 123456.789;
cout << fixed << number << endl;
cout << scientific << number << endl;
return 0;
}
6. hex, dec, and oct
• Function: Changes the number base for integer output. hex for hexadecimal,
dec for decimal, and oct for octal.
• Syntax: hex, dec, oct
• Example:
#include <iostream.h>
#include <iomanip> // For hex, dec, and oct
int main() {
int number = 255;
cout << hex << number << endl; // Hexadecimal
cout << dec << number << endl; // Decimal
cout << oct << number << endl; // Octal
return 0;
}
7. boolalpha and noboolalpha
• Function: Controls the display of boolean values. boolalpha prints true or false,
while noboolalpha prints 1 or 0.
• Syntax: boolalpha, noboolalpha
• Example:
#include <iostream.h>
#include <iomanip> // For boolalpha and noboolalpha
int main() {
bool flag = true;
cout << boolalpha << flag << endl; // Prints "true"
cout << noboolalpha << flag << endl; // Prints "1"
return 0;
}
Key Points:
• endl: Inserts a newline and flushes the stream.
• setw: Sets the width of the next field.
• setfill: Sets the fill character for fields.
• setprecision: Sets the precision for floating-point numbers.
• fixed and scientific: Control the format of floating-point numbers.
• hex, dec, and oct: Control the integer base format.
• boolalpha and noboolalpha: Control the boolean output format.
These manipulators are integral to formatting output in C++ and help in producing well-
structured and readable data presentations.
Type Casting
In C++, Type Casting can be performed using several different operators, each serving
a specific purpose. Here’s a breakdown of the type casting operators available in C++:
1. C-Style Cast
This is the traditional cast inherited from C and is the most general form of casting. It
tries different cast operations to convert the type.
int a = 10;
float b = (float)a; // C-style cast from int to float
2. static_cast
static_cast is used for conversions between types that are related by inheritance or are
of a known, safe conversion type. It is the most common cast used for basic type
conversions.
int a = 10;
float b = static_cast<float>(a); // static_cast from int to float
if (derivedPtr) {
// Successful cast
} else {
// Failed cast
}
4. const_cast
const_cast is used to add or remove const or volatile qualifiers from a variable. It is
useful when you need to modify a variable that was originally defined as const.
const int a = 10;
int* b = const_cast<int*>(&a); // Removing const qualifier
*b = 20; // Modifying the value
5. reinterpret_cast
reinterpret_cast is used for low-level casting that converts any pointer type to any other
pointer type. It’s often used for casting between incompatible types and should be used
with caution as it can lead to undefined behavior if not used properly.
int a = 65;
char* p = reinterpret_cast<char*>(&a); // Reinterpreting the int as char
Summary
• C-Style Cast: General cast, not type-safe, syntax: (target_type)value.
• static_cast: Safe for well-defined conversions, including basic type conversions
and class hierarchies.
• dynamic_cast: Used for safe downcasting and checking type at runtime
(requires polymorphism).
• const_cast: Adds or removes const or volatile qualifiers.
• reinterpret_cast: Low-level cast for converting between unrelated types, should
be used with care.
Each cast operator serves different purposes and should be chosen based on the type
of conversion and safety requirements.
Control Statements
If ... Else
C++ Conditions and If Statements
You already know that C++ supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
C++ has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of C++ code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the
condition is true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
Try it Yourself »
We can also test variables:
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
Try it Yourself »
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y
(using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18,
we print to the screen that "x is greater than y".
C++ Else
The else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of
this, we move on to the else condition and print to the screen "Good evening". If the
time was less than 18, the program would print "Good day".
Short Hand If Else
Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary operator because it
consists of three operands. It can be used to replace multiple lines of code with a single
line. It is often used to replace simple if else statements:
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
Switch Statements
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
The break Keyword
When C++ reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for
more testing.
While Loop
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more
readable.
While Loop
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a
variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:
Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
Another Example
This example will only print even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}