Unit 1 Principles of OOP: What Is OOPS?
Unit 1 Principles of OOP: What Is OOPS?
Unit 1 Principles of OOP: What Is OOPS?
Principles of OOP
What is OOPS?
Comparison Chart
BASIS FOR
POP C OOP C++
COMPARISON
Basis Main focus is on "how to get Main focus is on 'data security'. Hence,
the task done" i.e. on the only objects are permitted to access the
procedure or structure of a entities of a class.
program .
Division Large program is divided into Entire program is divided into objects.
units called functions.
Entity accessing No access specifier observed. Access specifier are "public", "private",
mode "protected".
1
BASIS FOR
POP C OOP C++
COMPARISON
Data hiding & There is no proper way of Data is hidden in three modes public,
security hiding the data, so data is private, and protected. hence data security
insecure increases.
Data sharing Global data is shared among Data is shared among the objects through
the functions in the program. the member functions.
Friend functions No concept of friend function. Classes or function can become a friend of
or friend classes another class with the keyword "friend".
Note: "friend" keyword is used only in c++
Virtual classes or No concept of virtual classes . Concept of virtual function appear during
virtual function inheritance.
2
Advantages
Disadvantages
3
Inheritance: Inheritance is a technique of acquiring features of objects
from one class to the other class objects. In other words, it helps in
deriving a new class from the existing one.
Polymorphism: Polymorphism provides a method of creating multiple
forms of a function by using a single function name.
Dynamic binding: It specifies that the code associated with a particular
procedure is not known until the moment of the call at run time.
Message passing: This OOP concept enables interaction between
different classes by transmitting and receiving information.
1) Class
The class is one of the Basic concepts of OOPs which is a group of similar entities. It is only
a logical component and not the physical entity. Lets understand this one of the OOPs
Concepts with example, if you had a class called “Expensive Cars” it could have objects like
Mercedes, BMW, Toyota, etc. Its properties (data) can be price or speed of these cars. While
the methods may be performed with these cars are driving, reverse, braking etc.
M
2) Object
An object can be defined as an instance of a class, and there can be multiple instances of a
class in a program. An Object is one of the Java OOPs concepts which contains both the data
and the function, which operates on the data. For example - chair, bike, marker, pen, table,
car, etc.
3) Inheritance
Inheritance is one of the Basic Concepts of OOPs in which one object acquires the properties
and behaviors of the parent object. It’s creating a parent-child relationship between two
classes. It offers robust and natural mechanism for organizing and structure of any software.
4) Polymorphism
Polymorphism refers to one of the OOPs concepts in Java which is the ability of a variable,
object or function to take on multiple forms. For example, in English, the verb run has a
different meaning if you use it with a laptop, a foot race, and business. Here, we understand
the meaning of run based on the other words used along with it. The same also applied to
Polymorphism.
5) Abstraction
Abstraction is one of the OOP Concepts in Java which is an act of representing essential
features without including background details. It is a technique of creating a new data type
that is suited for a specific application. Lets understand this one of the OOPs Concepts with
example, while driving a car, you do not have to be concerned with its internal working. Here
you just need to concern about parts like steering wheel, Gears, accelerator, etc.
4
6) Encapsulation
Encapsulation is one of the best Java OOPs concepts of wrapping the data and code. In this
OOPs concept, the variables of a class are always hidden from other classes. It can only be
accessed using the methods of their current class. For example - in school, a student cannot
exist without a class.
7) Association
Association is a relationship between two objects. It is one of the OOP Concepts in Java
which defines the diversity between objects. In this OOP concept, all object have their
separate lifecycle, and there is no owner. For example, many students can associate with one
teacher while one student can also associate with multiple teachers.
8) Aggregation
In this technique, all objects have their separate lifecycle. However, there is ownership such
that child object can’t belong to another parent object. For example consider class/objects
department and teacher. Here, a single teacher can’t belong to multiple departments, but even
if we delete the department, the teacher object will never be destroyed.
9) Composition
Composition is a specialized form of Aggregation. It is also called "death" relationship. Child
objects do not have their lifecycle so when parent object deletes all child object will also
delete automatically. For that, let’s take an example of House and rooms. Any house can have
several rooms. One room can’t become part of two different houses. So, if you delete the
house room will also be deleted.
OOPs Concepts in Java offer easy to understand and a clear modular structure for
programs.
Objects created for Object-Oriented Programs can be reused in other programs. Thus it
saves significant development cost.
Large programs are difficult to write, but if the development and designing team follow
OOPS concepts, then they can better design with minimum flaws.
It enhances program modularity because every object exists independently.
C verses Cpp
No. C C++
2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for outside
users.
5
approach.
5) In C, you can't use functions In C++, you can use functions in structure.
in structure.
10) C does not provide the C++ supports the feature of namespace.
feature of namespace.
11) Exception handling is not C++ provides exception handling using Try
easy in C. It has to perform and Catch block.
using other functions.
void main() {
cout << "Hello World!" << endl;
getch();
}
Output
Hello World
6
Standard libraries section
#include <iostream>
using namespace std;
#include is a specific preprocessor command that effectively copies and
pastes the entire text of the file, specified between the angle brackets, into the
source code.
The file <iostream>, which is a standard file that should come with the C++
compiler, is short for input-output streams. This command contains code
for displaying and getting an input from the user.
namespace is a prefix that is applied to all the names in a certain
set. iostream file defines two names used in this program - cout and endl.
This code is saying: Use the cout and endl tools from the std toolbox.
This function is called by the operating system when your program is executed
by the computer.
Symbols such as << can also behave like functions and are used with the
keyword cout.
After the return statement, execution control returns to the operating system
component that launched this program.
7
Token
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be
classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keywords: Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are trying
to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords.
However, you can specify the text to be substituted for keywords before compilation by using
C/C++ preprocessor directives. C language supports 32 keywords which are given below:
2.. Identifiers: Identifiers are used as the general terminology for the naming of variables,
functions and arrays. These are user-defined names consisting of an arbitrarily long sequence
of letters and digits with either a letter or the underscore(_) as a first character. Identifier
names must differ in spelling and case from any keywords. You cannot use keywords as
identifiers; they are reserved for special use. Once declared, you can use the identifier in later
program statements to refer to the associated value. A special kind of identifier, called a
statement label, can be used in goto statements.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore(_).
8
They must consist of only letters, digits, or underscore. No other special character is
allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
main: method name.
a: variable name.
3.. Constants: Constants are also like normal variables. But, the only difference is, their
values can not be modified by the program once they are defined. Constants refer to fixed
values. They are also called literals. Constants may belong to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
Integer constants – Example: 0, 1, 1218, 12482
Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal:
(013)16 = (19)10
Character constants -Example: ‘a’, ‘A’, ‘z’
String constants -Example: “GeeksforGeeks”
4.. Strings: Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in double-
quotes. Whereas, a character is enclosed in single quotes in C and C++.Declarations for
String:
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
when we declare char as “string[20]”, 20 bytes of memory space is allocated
for holding the string value.
When we declare char as “string[]”, memory space will be allocated as per the
requirement during the execution of the program.
5.. Special Symbols: The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #
Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and
function parameters.
Braces{}: These opening and ending curly braces mark the start and end of a
block of code containing more than one executable statement.
Comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
Colon(:): It is an operator that essentially invokes something called an
initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of
one logical entity. That’s why each individual statement must be ended with a
semicolon.
Asterisk (*): It is used to create a pointer variable.
Assignment operator(=): It is used to assign values.
9
Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
6.. Operators: Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
Unary Operators: Those operators that require only a single operand to act
upon are known as unary operators.For Example increment and decrement
operators
Binary Operators: Those operators that require two operands to act upon are
called binary operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
Ternary Operators: ? :
C++ Variables
Variables are containers for storing data values. In C++, there are different types of variables
(defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
string - stores text, such as "Hello World". String values are surrounded by double
quotes
bool - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Syntax
type variable = value;
Where type is one of C++ types (such as int), and variable is the name of the variable (such
as x or myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
10
Basic Data Type and User Defined Data Types:
All variables use data-type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data it
can store. Whenever a variable is defined in C++, the compiler allocates some memory
for that variable based on the data-type with which it is declared. Every data type
requires a different amount of memory.
11
Data types in C++ is mainly divided into three types:
1. Primitive Data Types: These data types are built-in or predefined data types and can
be used directly by the user to declare variables. example: int, char , float, bool etc.
Primitive data types available in C++ are:
Integer
Character
Boolean
Floating Point
Double Floating Point
Valueless or Void
Wide Character
2. Derived Data Types: The data-types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types. These can be of four types namely:
Function
Array
Pointer
Reference
3. Abstract or User-Defined Data Types: These data types are defined by user itself.
Like, defining a class in C++ or a structure. C++ provides the following user-defined
datatypes:
Class
Structure
12
Union
Enumeration
Typedef defined DataType
This article discusses primitive data types available in C++.
Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes
of memory space and ranges from -2147483648 to 2147483647.
Character: Character data type is used for storing characters. Keyword used for
character data type is char. Characters typically requires 1 byte of memory space and
ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical values. A boolean
variable can store either true or false. Keyword used for boolean data type is bool.
Floating Point: Floating Point data type is used for storing single precision floating
point values or decimal values. Keyword used for floating point data type is float. Float
variables typically requires 4 byte of memory space.
Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating
point data type is double. Double variables typically requires 8 byte of memory space.
void: Void means without any value. void datatype represents a valueless entity. Void
data type is used for those function which does not returns a value.
Wide Character: Wide character data type is also a character data type but this data
type has size greater than the normal 8-bit datatype. Represented by wchar_t. It is
generally 2 or 4 bytes long.
void main()
{
cout << "Size of char : " << sizeof(char)
<< " byte" << endl;
cout << "Size of int : " << sizeof(int)
<< " bytes" << endl;
cout << "Size of short int : " << sizeof(short int)
<< " bytes" << endl;
cout << "Size of long int : " << sizeof(long int)
<< " bytes" << endl;
cout << "Size of signed long int : " << sizeof(signed long int)
<< " bytes" << endl;
cout << "Size of unsigned long int : " << sizeof(unsigned long int)
<< " bytes" << endl;
cout << "Size of float : " << sizeof(float)
<< " bytes" <<endl;
cout << "Size of double : " << sizeof(double)
<< " bytes" << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t)
13
<< " bytes" <<endl;
Getch();
}
Type Casting:
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to avoid
lose of data.
All the data types of the variables are upgraded to the data type of the variable
with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long
is implicitly converted to float).
Example of Type Implicit Conversion:
// An example of implicit conversion
#include<iostream.h>
#include<conio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
getch();
}
Output:
x = 107
y = a
z = 108
14
2. Explicit Type Conversion: This process is also called type casting and it is user-
defined. Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly defining the required type in front of the
expression in parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:
Operators:
An operator is a symbol that operates on a value or a variable.
Operators are symbols that perform operations on variables and values. For
example, + is an operator used for addition, while - is an operator used for
subtraction.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
15
1. C++ Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and
data. For example,
a + b;
Here, the + operator is used to add two variables a and b . Similarly there are
various other arithmetic operators in C++.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
#include <iostream>
16
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
return 0;
}
Output
a + b = 9
a - b = 5
a * b = 14
a / b = 3
a % b = 1
17
In C++,
7/2 is 3
7.0 / 2 is 3.5
7 / 2.0 is 3.5
7.0 / 2.0 is 3.5
% Modulo Operator
The modulo operator % computes the remainder. When a = 9 is divided by b = 4,
int num = 5;
// increasing num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.
Example 2: Increment and Decrement Operators
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 100, result_a, result_b;
18
// decrementing b by 1 and storing the result in result_b
result_b = --b;
cout << "result_b = " << result_b << endl;
return 0;
}
Output
result_a = 11
result_b = 99
In the above program, we used ++ and -- operator as prefixes. We can also use
these operators as postfix.
There is a slight difference when these operators are used as a prefix versus when
they are used as a postfix.
// assign 5 to a
a = 5;
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
19
Example 2: Assignment Operators
#include <iostream>
using namespace std;
int main() {
int a, b, temp;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
return 0;
}
Output
temp = 2
a = 9
Here, > is a relational operator. It checks if a is greater than b or not.
If the relation is true, it returns 1 whereas if the relation is false, it returns 0.
Operator Meaning Example
20
== Is Equal To 3 == 5 gives us false
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 3;
b = 5;
bool result;
return 0;
}
21
Output
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
Logical OR.
expression1 ||
|| True if at least one of the operands is
expression2
true.
Logical NOT.
! !expression
True only if the operand is false.
Suppose,
a = 5
b = 8
Then,
22
!(a == 3) evaluates to true
!(a > 3) evaluates to false
#include <iostream>
using namespace std;
int main() {
bool result;
return 0;
}
Output
(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
23
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 < 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0
< 5) are 1 (true).
5) is 0 (false).
> 5) are 0 (false).
< 5) are 1 (true).
5) is 1 (true).
> 5) are 0 (false).
| Binary OR
^ Binary XOR
24
~ Binary One's Complement
Expressions:
Example:
a+b
c
s-1/7*f
.
.
etc
Types of Expressions:
Expressions may be of the following types:
25
Constant expressions: Constant Expressions consists of only constant values. A constant
value is one that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’
Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
Floating expressions: Float Expressions are which produce floating point results after
implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
Relational expressions: Relational Expressions yield results of type bool which takes a value
true or false. When arithmetic expressions are used on either side of a relational operator, they
will be evaluated first and then the results compared. Relational expressions are also known as
Boolean expressions.
Examples:
x <= y, x + y > 2
Logical expressions: Logical Expressions combine two or more relational expressions and
produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
26
Pointer expressions: Pointer Expressions produce address values.
Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are
basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.
Control Structures:
With the introduction of control sequences we are going to have to introduce a new
concept: the block of instructions. A block of instructions is a group of
instructions separated by semicolons ( ;) but grouped in a block delimited by curly
bracket signs: { and }.
27
Most of the control structures that we will see in this section allow a
generic statement as a parameter, this refers to either a single instruction or a block
of instructions, as we want. If we want the statement to be a single instruction we
do not need to enclose it between curly-brackets ( {}). If we want the statement to
be more than a single instruction we must enclose them between curly brackets
({}) forming a block of instructions.
Conditional structure: if and else
It is used to execute an instruction or block of instructions only if a condition is
fulfilled. Its form is:
if (condition) statement
For example, the following code fragment prints out x is 100 only if the value
stored in variable x is indeed 100:
if (x == 100)
cout << "x is 100";
We can additionally specify what we want that happens if the condition is not
fulfilled by using the keyword else. Its form used in conjunction with if is:
if (condition) statement1 else statement2
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only
if not- it prints out x is not 100.
28
The if + else structures can be concatenated with the intention of verifying a range
of values. The following example shows its use telling if the present value stored
in x is positive, negative or none of the previous, that is to say, equal to zero.
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
When the program starts the user is prompted to insert a starting number for
the countdown. Then the while loop begins, if the value entered by the user
29
fulfills the condition n>0 (that n be greater than 0 ), the block of instructions
that follows will execute an indefinite number of times while the
condition (n>0) remains true.
All the process in the program above can be interpreted according to the
following script: beginning in main:
--n;
(prints out n on screen and decreases n by 1).
We must consider that the loop has to end at some point, therefore, within
the block of instructions (loop's statement) we must provide some method
that forces condition to become false at some moment, otherwise the loop
will continue looping forever. In this case we have included --n; that causes
the condition to become false after some loop repetitions:
when n becomes 0, that is where our countdown ends.
Of course this is such a simple action for our computer that the whole
countdown is performed instantly without practical delay between numbers.
The do-while loop.
Format:
do statement while (condition);
30
#include <iostream.h> You entered: 12345
int main () Enter number (0 to end): 160277
{ You entered: 160277
unsigned long n; Enter number (0 to end): 0
do { You entered: 0
cout << "Enter number (0 to
end): ";
cin >> n;
cout << "You entered: " << n
<< "\n";
} while (n != 0);
return 0;
}
The for loop.
Its format is:
for (initialization; condition; increase) statement;
31
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
Optionally, using the comma operator (,) we can specify more than one
instruction in any of the fields included in a for loop, like
in initialization, for example. The comma operator (,) is an instruction
separator, it serves to separate more than one instruction where only one
instruction is generally expected. For example, suppose that we wanted to
intialize more than one variable in our loop:
for ( n=0, i=100 ; n!=i ; n++, i-- )
{
// whatever here...
}
This loop will execute 50 times if neither n nor i are modified within the
loop:
32
// break loop example 10, 9, 8, 7, 6, 5, 4, 3,
#include <iostream.h> countdown aborted!
int main ()
{
int n;
for (n=10; n>0; n--) {
cout << n << ", ";
if (n==3)
{
cout << "countdown
aborted!";
break;
}
}
return 0;
}
The continue instruction.
The continue instruction causes the program to skip the rest of the loop in
the present iteration as if the end of the statement block would have been
reached, causing it to jump to the following iteration. For example, we are
going to skip the number 5 in our countdown:
// break loop example 10, 9, 8, 7, 6, 4, 3, 2, 1,
#include <iostream.h> FIRE!
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
The goto instruction.
It allows making an absolute jump to another point in the program. You
should use this feature carefully since its execution ignores any type of
nesting limitation.
33
// goto loop example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
#include <iostream.h> FIRE!
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!";
return 0;
}
The exit function.
exit is a function defined in cstdlib (stdlib.h) library.
The purpose of exit is to terminate the running program with an specific exit
code. Its prototype is:
void exit (int exit code);
34
structure.
If expression was not equal to constant1 it will check if expression is equivalent
to constant2. If it is, it will execute block of instructions 2 until it finds
the break keyword.
Finally, if the value of expression has not matched any of the previously specified
constants (you may specify as many case sentences as values you want to check),
the program will execute the instructions included in the default: section, if this
one exists, since it is optional.
switch example if-else equivalent
switch (x) { if (x == 1) {
case 1: cout << "x is 1";
cout << "x is 1"; }
break; else if (x == 2) {
case 2: cout << "x is 2";
cout << "x is 2"; }
break; else {
default: cout << "value of x unknown";
cout << "value of x }
unknown";
}
switch (x) {
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default:
cout << "x is not 1, 2 nor 3";
}
35
Notice that switch can only be used to compare an expression with
different constants. Therefore we cannot put variables (case (n*2):) or ranges
(case (1..3):) because they are not valid constants.
If you need to check ranges or values that are not constants use a concatenation
of if and else if sentences.
The :: (scope resolution) operator is used to get hidden names due to variable
scopes so that you can still use them. The scope resolution operator can be used as
both unary and binary. You can use the unary scope operator if a namespace scope
or global scope name is hidden by a particular declaration of an equivalent name
during a block or class. For example, if you have a global variable of name my_var
and a local variable of name my_var, to access global my_var, you'll need to use
the scope resolution operator.
Example
#include <iostream>
int my_var = 0;
int main(void) {
int my_var = 0;
return 0;
Output
This will give the output −
1, 2
The declaration of my_var declared in the main function hides the integer named
my_var declared in global namespace scope. The statement ::my_var = 1 accesses
the variable named my_var declared in global namespace scope.
36
You can also use the scope resolution operator to use class names or class member
names. If a class member name is hidden, you can use it by prefixing it with its class
name and the class scope operator. For example,
Example
#include <iostream>
class X {
public:
};
int main () {
Output
This will give the output −
10
1) To access a global variable when there is a local variable with same name:
int main()
37
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Output:
Value of global x is 0
Value of local x is 10
#include<iostream>
class A
public:
void fun();
};
void A::fun()
int main()
A a;
a.fun();
38
return 0;
Output:
fun() called
#include<iostream>
class Test
public:
{
}
};
// like this
int Test::x = 1;
int Test::y = 2;
39
int main()
Test obj;
int x = 3 ;
obj.func(x);
return 0;
Output:
Value of static x is 1
Value of local x is 3
Test::y = 2;
#include<iostream>
class A
protected:
int x;
public:
A() { x = 10; }
};
class B
40
protected:
int x;
public:
B() { x = 20; }
};
public:
void fun()
{
}
};
int main()
C c;
c.fun();
return 0;
Output:
A's x is 10
B's x is 20
5) For namespace
If a class having the same name exists inside two namespace we can use the namespace name
with the scope resolution operator to refer that class without any conflicts
#include<iostream>
int main(){
41
#include<iostream>
class outside
public:
int x;
class inside
{
public:
int x;
int foo();
};
};
int main(){
outside A;
outside::inside B;
Arrays can be used to store multiple homogenous data but there are serious drawbacks of
using arrays.
Programmer should allocate the memory of an array when they declare it but most of time,
the exact memory needed cannot be determined until runtime.
The best thing to do in this situation is to declare the array with maximum possible memory
required (declare array with maximum possible size expected) but this wastes memory.
42
So, To avoid wastage of memory, you can dynamically allocate the memory required during
runtime using new and delete operator.
What are memory management operators?
There are two types of memory management operators in C++:
new
delete
These two memory management operators are used for allocating and freeing memory blocks in efficient
and convenient ways.
New operator:
The new operator in C++ is used for dynamic storage allocation. This operator can be used to
create object of any type.
In the above statement, new is a keyword and the pointer variable is a variable of type datatype.
For example:
1. int *a = new int;
2. *a = 20;
or
3. int *a = new int(20);
In the above example, the new operator allocates sufficient memory to hold the object of
datatype int and returns a pointer to its starting point.
the pointer variable a holds the address of memory space allocated.
delete operator:
The delete operator in C++ is used for releasing memory space when the object is no longer
needed.
Once a new operator is used, it is efficient to use the corresponding delete operator for release
of memory.
Example:
#include <iostream>
43
void main()
{
//Allocates using new operator memory space in memory for storing a integer
datatype
int *a= new int;
*a=100;
cout << " The Output is:a= " << *a;
//Memory Released using delete operator
delete a;
}
Output:
The Output is:a=100
Arrays
Arrays in C/C++
An array in C or C++ is a collection of items stored at contiguous memory locations and
elements can be accessed randomly using indices of an array. They are used to store similar
type of elements as in the data type must be the same for all elements. They can be used to store
collection of primitive data types such as int, float, double, char, etc of any particular type. To
add to it, an array in C or C++ can store derived data types such as the structures, pointers etc.
44
Given below is the picturesque representation of an array.
Note: In above image int a[3]={[0…1]=3}; this kind of declaration has been obsolete since
GCC 2.5
There are various ways in which we can declare an array. It can be done by specifying its type
and size, by initializing it or both.
Array declaration by specifying size
int arr1[10];
45
// With recent C/C++ versions, we can also
int n = 10;
int arr2[n];
// elements
// 0. above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"
46
Example:
#include <stdio.h>
int main()
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3] = arr[0];
printf("%d %d %d %d", arr[0],
return 0;
// is not checked in C.
47
#include <stdio.h>
int main()
{
int arr[2];
return 0;
Output
-449684907 4195777
In C, it is not compiler error to initialize an array with more elements than the specified size.
For example, the below program compiles fine and shows just Warning.
#include <stdio.h>
int main()
// Array declaration by initializing it
return 0;
Warnings:
prog.c: In function 'main':
prog.c:7:25: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:25: note: (near initialization for 'arr')
prog.c:7:29: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:29: note: (near initialization for 'arr')
prog.c:7:33: warning: excess elements in array initializer
int arr[2] = { 10, 20, 30, 40, 50 };
^
prog.c:7:33: note: (near initialization for 'arr')
48
Note: The program won’t compile in C++. If we save the above program as a .cpp, the
program generates compiler error “error: too many initializers for ‘int [2]'”.
The elements are stored at contiguous memory locations
Example:
// contiguous locations
#include <stdio.h>
int main()
int arr[5], i;
printf("Size of integer in this compiler is %lu\n",
sizeof(int));
for (i = 0; i < 5; i++)
return 0;
Output
Size of integer in this compiler is 4
Address arr[0] is 0x7ffe75c32210
Address arr[1] is 0x7ffe75c32214
Address arr[2] is 0x7ffe75c32218
49
Address arr[3] is 0x7ffe75c3221c
Address arr[4] is 0x7ffe75c32220
#include<bits/stdc++.h>
int main()
int arr[6]={11,12,13,14,15,16};
// Way -1
for(int i=0;i<6;i++)
cout<<arr[i]<<" ";
cout<<endl;
// Way 2
for(int i=0;i<6;i++)
cout<<i[arr]<<" ";
cout<<endl;
return 0;
}
// Contributed by Akshay Pawar ( Username - akshaypawar4)
Output
11 12 13 14 15 16
By Other Method:
11 12 13 14 15 16
String
50
Example 1
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello";
cout << greeting;
return 0;
}
Example 2
#include <iostream>
int main () {
return 0;
}
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0
51
if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
#include <iostream>
#include <cstring>
int main () {
getch();
}
When the above code is compiled and executed, it produces result something as
follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Structures in c++
Structure is a compound data type that contains different variables of different types.
For example, you want to store Student details like student name, student roll num,
student age. You have two ways to do it, one way is to create different variables for
each data, but the downfall of this approach is that if you want to store the details of
52
multiple students, in that case it is not feasible to create separate set of variables for
each student.
The second and best way of doing it by creating a structure like this:
struct Student
{
char stuName[30];
int stuRollNo;
int stuAge;
};
Now these three members combined will act like a separate variable and you can
create structure variable like this:
structure_name variable_name
So if you want to hold the information of two students using this structure then you
can do it like this:
Similarly I can set and get the values of other data members of the structure for
every student. Lets see a complete example to put this up all together:
#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
int main(){
Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
cout<<"ENter Student Roll No: ";
cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;
53
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge;
return 0;
}
Output:
1. struct structure_name
2. {
3. // member declarations.
4. }
Example:
1. struct Student
2. {
3. char name[20];
4. int id;
5. int age;
6. }
1. #include <iostream>
2. using namespace std;
3. struct Rectangle {
4. int width, height;
5. Rectangle(int w, int h)
6. {
7. width = w;
8. height = h;
9. }
10. void areaOfRectangle() {
11. cout<<"Area of Rectangle is: "<<(width*height); }
12. };
13. int main(void) {
14. struct Rectangle rec=Rectangle(4,6);
15. rec.areaOfRectangle();
54
16. return 0;
17. }
Output:
55