Friday, June 12, 2020

Programming In C++

What is Procedural Programming?
Definition:
  • Procedural Programming may be the first programming paradigm.
  • Fundamentally, the procedural code is the one that directly instructs a device on how to finish a task in logical steps.
  • This paradigm uses a linear top-down approach and treats data and procedures as two different entities.
  • Based on the concept of a procedure call, Procedural Programming divides the program into procedures, which are also known as routines or functions, simply containing a series of steps to be carried out.
  • Simply Says, Procedural Programming involves writing down a list of instructions to tell the computer what it should do step-by-step to finish the task at hand.

Key Features of Procedural Programming

    The key features of procedural programming are given below:
  • Predefined functions: A predefined function is typically an instruction identified by a name. Usually, the predefined functions are built into higher-level programming languages, but they are derived from the library or the registry, rather than the program. One example of a pre-defined function is ‘charAt()’, which searches for a character position in a string.


  • Local Variable: A local variable is a variable that is declared in the main structure of a method and is limited to the local scope it is given. The local variable can only be used in the method it is defined.

  • Global Variable: A global variable is a variable which is declared outside every other function defined in the code. Due to this, global variables can be used in all functions, unlike a local variable.

  • Modularity: Modularity is when two dissimilar systems have two different tasks at hand but are grouped together to conclude a larger task first. Every group of systems then would have its own tasks finished one after the other until all tasks are complete.

  • Parameter Passing: Parameter Passing is a mechanism used to pass parameters to functions, subroutines or procedures. Parameter Passing can be done through ‘pass by value’, ‘pass by reference’, ‘pass by result’, ‘pass by value-result’ and ‘pass by the name’.


Advantages and Disadvantages of Procedural Programming

Advantages

  • Procedural Programming is excellent for general-purpose programming
  • The coded simplicity along with ease of implementation of compilers and interpreters
  • A large variety of books and online course material available on tested algorithms, making it easier to learn along the way
  • The source code is portable, therefore, it can be used to target a different CPU as well
  • The code can be reused in different parts of the program, without the need to copy it
  • Through Procedural Programming technique, the memory requirement also slashes
  • The program flow can be tracked easily

Disadvantages

  • The program code is harder to write when Procedural Programming is employed
  • The Procedural code is often not reusable, which may pose the need to recreate the code if is needed to use in another application
  • Difficult to relate with real-world objects
  • The importance is given to the operation rather than the data, which might pose issues in some data-sensitive cases
  • The data is exposed to the whole program, making it not so much security friendly

What Is Object-Oriented Programming (OOP)

OOP is an approach to programming which recognizes life as we know it as a collection of objects, which work in tandem with each other to solve a particular problem at hand. The primary thing to know about OOP is encapsulation, which is the idea that each object which holds the program is self-sustainable, which means that all the components that make up the object are within the object itself. Now since each module within this paradigm is self-sustainable, objects can be taken from one program and used to resolve another problem at hand with little or no alterations.
Principles of OOP
Object-oriented programming is based on the following principles:
Encapsulation, data hiding ,Abstraction. Inheritance, Polymorphism.

Advantages

  • Due to modularity and encapsulation, OOP offers ease of management
  • OOP mimics the real world, making it easier to understand
  • Since objects are whole within themselves, they are reusable in other programs

Disadvantages

  • Object-Oriented programs tend to be slower and use up a high amount of memory
  • Over-generalization
  • Programs built using this paradigm may take longer to be create

C++ OOPs Concepts

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
    • Object
    • Class
    • Inheritance
    • Polymorphism
    • Abstraction
    • Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.
In C++, we use Function overloading and Function overriding to achieve polymorphism.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.
In C++, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.
Difference between OOP and POP:

OOP
POP
Object oriented.
Structure oriented.
Program is divided into objects.
Program is divided into functions.
Bottom-up approach.
Top-down approach.
Inheritance property is used.
Inheritance is not allowed.
It uses access specifier.
It doesn’t use access specifier.
Encapsulation is used to hide the data.
No data hiding.
Concept of virtual function.
No virtual function.
C++, Java.
C, Pascal.

Applications of Object Oriented Programming

Main application areas of OOP are:
  • User interface design such as windows, menu.
  • Real Time Systems
  • Simulation and Modeling
  • Object oriented databases
  • AI and Expert System
  • Neural Networks and parallel programming
  • Decision support and office automation systems etc.

Benefits of OOP:

  • It is easy to model a real system as real objects are represented by programming objects in OOP. The objects are processed by their member data and functions. It is easy to analyze the user requirements.
  • With the help of inheritance, we can reuse the existing class to derive a new class such that the redundant code is eliminated and the use of existing class is extended. This saves time and cost of program.
  • In OOP, data can be made private to a class such that only member functions of the class can access the data. This principle of data hiding helps the programmer to build a secure program that can not be invaded by code in other part of the program.
  • With the help of polymorphism, the same function or same operator can be used for different purposes. This helps to manage software complexity easily.
  • Large problems can be reduced to smaller and more manageable problems. It is easy to partition the work in a project based on objects.
  • It is possible to have multiple instances of an object to co-exist without any interference i.e. each object has its own separate member data and function.

C++ Programming

C++ is a high-level, object-oriented, general-purpose programming language. Not only does C++ support the latest features that represent real-world problems, but it also supports the implementation of low-level manipulation problems.

 

Features of C++

·         Object-oriented programming (OOP): The major reason for the popularity of C++ is that it efficiently supports the concept of OOP. These include data abstraction and encapsulation, data hiding, inheritance, and polymorphism.

·         Platform independent and portable: C++ is supported on any platform, may it be Windows or Linux.

·         Simple: The syntax of C++ is pretty similar to the English language and hence it is easily comprehensible.

·         High-level programming language: Since the addition of features to C and Simula 67, the first object-oriented language led to the development of C++, it is regarded as a high-level programming language.

·         Case-sensitive: Uppercase and lowercase characters are treated differently in C++, giving the user a wide range of choice of seemingly similar identifier names.

·         Compiler-based: The C++ language has a compiler to compile the program before we run it.

·         DMA: DMA stands for Dynamic Memory Allocation in which we can choose the size of variables or Data Structures at the run-time of the program.

·         Existence of Libraries: We can access the wide range of functions available in C++ with the help of the Standard C++ Library.

·         Speed: Since C++ is compiler-based, it inevitably proves to be much faster than Python and Java which are interpreter-based.

 

How to write a Program in C++?

Here is a very simple program to print “Hello World!” on the display screen for you to get started with C++:

1.     #include<iostream>

2.     using namespace std;

3.      

4.     /* This is my first C++ program */

5.      

6.     int main()

7.     {

8.     cout<<"Hello world!"<<endl;

9.     return 0;

10.    }

Header Files in C++

The first component of every C++ program is essentially a header file. In the “Hello world!” program, we have used the following header file which is mandatory in every C++ program.

#include<iostream>

Here, ‘iostream’ refers to the input-output stream.

In the above program, we used it to display the output with the help of the ‘cout’ function.

Namespace

It provides a region for a declaration that provides scope to all the identifiers inside it.

using namespace std;

The Main Function

Every program in C++ contains at least one function, that is, the main function.

The curly braces ‘{’ and ‘}’ indicate the beginning and end of a block of statements respectively.

Print Statement

We use the ‘cout’ statement to display a text on the screen.

cout<<“Hello world!”<<endl;

return 0;

We use the return 0 statement to indicate that the main function should return a null value.

 

Advantages and Disadvantages of C++

Advantages of C++

·         Portability:  C++ offers the feature of portability or platform independence which allows the user to run the same program on different operating systems or interfaces at ease.

·         Object-oriented: One of the biggest advantages of C++ is the feature of object-oriented programming which includes concepts like classes, inheritance, polymorphism, data abstraction, and encapsulation that allow code reusability and makes a program+ even more reliable

·         Multi-paradigm: C++ is a multi-paradigm programming language. The term “Paradigm” refers to the style of programming. It includes logic, structure, and procedure of the program. There are three paradigms followed by C++. They are Generic, Imperative, object-oriented.

·         Large community support: C++ has a large community that supports it by providing online courses and lectures, both paid and unpaid.

·         Compatibility with C: C++ is pretty much compatible with C. Virtually, every error-free C program is a valid C++ program.

·         Scalability: Applications that are very resource intensive are usually built in C++

Disadvantages of C++

·         Use of pointers: Pointers is a relatively difficult concept to grasp and it consumes a lot of memory.

·         Security issues: Although object-oriented programming offers a lot of security to the data being handled as compared to other programming languages that are not object-oriented, like C, certain security issues still exist due to the availability of friend functions, global variables and, pointers.

·         Absence of Garbage collector:  C++ gives the user complete control of managing the computer memory using DMA. C++ lacks the feature of a garbage collector to automatically filter out unnecessary data.

·         Absence of built-in threads: C++ does not support any built-in threads.

 

C++ Character Set

C++ Character set is basically a set of valid characters that convey a specific connotation to the compiler. We use characters to represent letters, digits, special symbols, white spaces, and other characters.

The C++ character set consists of 3 main elements. They are:

1.     Letters: These are alphabets ranging from A-Z and a-z (both uppercase and lowercase characters convey different meanings)

2.     Digits: All the digits from 0 – 9 are valid in C++.

3.     Special symbols: There are a variety of special symbols available in C++ like mathematical, logical and relational operators like +,-, *, /, \, ^, %, !, @, #, ^, &, (, ), [, ], ; and many more.

 

Tokens in C++

Tokens in C++ are the smallest individual unit of a program.

The following tokens are available in C++ which are similar to that seen in C with the addition of certain exclusive keywords, strings, and operators:

·         Keywords

·         Identifiers

·         Constants

·         Strings

·         Special symbols

·         Operators

 

Keywords

alignas

alignof

asm

auto

bool

break

case

catch

char

char16_t

char32_t

class

const

constexpr

const_cast

continue

decltype

default

delete

double

do

dynamic_cast

else

enum

explicit

export

extern

FALSE

float

for

friend

goto

if

inline

int

long

mutable

namespace

new

noexcept

nullptr

operator

private

protected

public

register

reinterpret_cast

return

short

signed

sizeof

static

static_assert

static_cast

struct

switch

template

this

thread_local

throw

TRUE

try

typedef

typeid

typename

union

unsigned

using

virtual

void

volatile

wchar_t

while

It is important to note that we cannot use C++ keywords for assigning variable names as it would suggest a totally different meaning entirely and would be incorrect.

Identifiers

C++ allows the programmer to assign names of his own choice to variables, arrays, functions, structures, classes, and various other data structures called identifiers. The programmer may use the mixture of different types of character sets available in C++ to name an identifier.

Rules for C++ Identifiers

There are certain rules to be followed by the user while naming identifiers, otherwise, you would get a compilation error. These rules are:

1.     First character: The first character of the identifier in C++ should positively begin with either an alphabet or an underscore. It means that it strictly cannot begin with a number.

2.     No special characters: C++ does not encourage the use of special characters while naming an identifier. It is evident that we cannot use special characters like the exclamatory mark or the “@” symbol.

3.     No keywords: Using keywords as identifiers in C++ is strictly forbidden, as they are reserved words that hold a special meaning to the C++ compiler. If used purposely, you would get a compilation error.

4.     No white spaces: Leaving a gap between identifiers is discouraged. White spaces incorporate blank spaces, newline, carriage return, and horizontal tab.

5.     Word limit: The use of an arbitrarily long sequence of identifier names is restrained. The name of the identifier must not exceed 31 characters, otherwise, it would be insignificant.

6.     Case sensitive: In C++, uppercase and lowercase characters connote different meanings.

Here is a table which illustrates the valid use of Identifiers:

Identifier Name

Valid or Invalid

Correction or alternative, if invalid 

Elucidation if invalid 

5th_element

Invalid

element_5

It violates Rule 1 as it begins with a digit

_delete

Valid

school.fee

Invalid

school_fee

It violates Rule 2 as it contains a special character ‘.’

register[5]

Invalid

Register[5]

It violates Rule 3 as it contains a keyword

Student[10]

Valid

employee name

Invalid

employee _name

It violates Rule 4 as it contains a blank space

perimeter()

Valid

Constants

As the name itself suggests, constants are referred to as fixed values that cannot change their value during the entire program run as soon as we define them.

Syntax:

const data_type variable_name = value;

Types of Constants in C++

The different types of constants are:

·         Integer constants – These constants store values of the int data type.

For instance:

const int data = 5;

·         Floating constants – These constants store values of the float data type.

For instance:

const float e = 2.71;

·         Character constants – These constants store values of the character data type.

For instance:

const char answer = ‘y’;

·         String constants – These constants are also of the character data type but differ in the declaration part.

For instance:

const char title[] = ‘‘DataFlair’’;

·         Octal constants – The number system which consists of only 8 digits, from 0 to 7 is called the octal number system. The constant octal values can be declared as:

const int oct = 034;

·         Hexadecimal constants – The number system which consists of 16 digits, from 0 to 9 and alphabets ‘a’ to ‘f’ is called hexadecimal number system. The constant hexadecimal values can be declared as:

const int hex = 0x40;

Strings

Just like characters, strings in C++ are used to store letters and digits. Strings can be referred to as an array of characters as well as an individual data type.

It is enclosed within double quotes, unlike characters which are stored within single quotes. The termination of a string in C++ is represented by the null character, that is, ‘\0’. The size of a string is the number of individual characters it has.

In C++, a string can be declared in the following ways:

char name[30] = ‘’Hello!”; // The compiler reserves 30 bytes of memory for the string.

char name[] = “Hello!”; // The compiler reserves the required amount of memory for the string.

char name[30] = { ‘H’ , ’e’ , ’l’ , ’l’ , ’o’};; // This is how a string is represented as a set of characters.

string name = “Hello” // The compiler reserves 32 bytes of memory.

Special Symbols

Apart from letters and digits, there are some special characters in C++ which help you manipulate or perform data operations. Each special symbol has a specific meaning to the C++ compiler.

Here is a table which illustrates some of the special characters in C:

Special Character

Trivial Name

Function

[ ]

Square brackets

The opening and closing brackets of an array symbolize single and multidimensional subscripts.

()

Simple brackets

The opening and closing brackets represent function declaration and calls, used in print statements.

{ }

Curly braces

The opening and closing curly brackets to denote the start and end of a particular fragment of code which may be functions, loops or conditional statements

,

Comma

We use commas to separate more than one statements, like in the declaration of different variable names

#

Hash / Pound / Preprocessor

The hash symbol represents a preprocessor directive used for denoting the use of a header file

*

Asterisk

We use the asterisk symbol in various respects such as to declare pointers, used as an operand for multiplication

~

Tilde

We use the tilde symbol as a destructor to free memory

.

Period / dot

The use the dot operator to access a member of a structure

Operators

Operators are tools or symbols which are used to perform a specific operation on data. Operations are performed on operands. Operators can be classified into three broad categories according to the number of operands used.

Unary: It involves the use of one a single operand. For instance, ’!’ is a unary operator which operates on a single variable, say ‘c’ as !c which denotes its negation or complement.

Binary: It involves the use of 2 operands. They are further classified as:

·         Arithmetic

·         Relational

·         Logical

·         Assignment

·         Bitwise

·         Conditional

Ternary: It involves the use of 3 operands. For instance, ?: is used to in place of if-else conditions.

Types of Operators in C++

 

Arithmetic Operators

It includes basic arithmetic operations like addition, subtraction, multiplication, division, modulus operations, increment, and decrement.

1.      + (Addition) – This operator is used to add two operands.

2.     – (Subtraction) – Subtract two operands.

3.     * (Multiplication) – Multiply two operands.

4.     / (Division) – Divide two operands and gives the quotient as the answer.

5.     % (Modulus operation) – Find the remains of two integers and gives the remainder after the division.

6.     ++ (Increment) – Used to increment an operand.

7.     — (Decrement) – Used to decrement an operand.

 

Table for Arithmetic Operators in C++

Operator

 

Operand

Operation

Elucidation

+

 

a, b

a + b

Addition

 

a, b

a – b

Subtraction

*

 

a, b

a * b

Multiplication

/

 

a, b

a / b

Division

%

 

a, b

a % b

Modulus operator – to find the remainder when two integral digits are divided

++

 

a

a ++

Increment

 

a

a – –

Decrement

Relational Operators

It is used to compare two numbers by checking whether they are equal or not, less than, less than or equal to, greater than, greater than or equal to.

1.     == (Equal to)– This operator is used to check if both operands are equal.

2.     !=  (Not equal to)– Can check if both operands are not equal.

3.     > (Greater than)– Can check if the first operand is greater than the second.

4.     < (Less than)- Can check if the first operand is lesser than the second.

5.     >=  (Greater than equal to)– Check if the first operand is greater than or equal to the second.

6.     <= (Less than equal to)– Check if the first operand is lesser than or equal to the second

If the relational statement is satisfied (it is true), then the program will return the value 1, otherwise, if the relational statement is not satisfied (it is false), the program will return the value 0.

Table for Relational Operators in C and C++

 Operator

Operand

Operation

Elucidation

==

a, b

(a==b)

Used to check if both operands are equal

!=

a, b

(a!=b)

Used to check if both operands are not equal

> 

a, b

(a>b)

Used to check if the first operand is greater than the second

< 

a, b

(a<b)

Used to check if the first operand is lesser than the second

>=

a, b

(a>=b)

Used to check if the first operand is greater than or equal to the second

<=

a, b

(a<=b)

Used to check if the first operand is lesser than or equal to the second

Logical Operators

It refers to the boolean values which can be expressed as:

·         Binary logical operations, which involves two variables: AND and OR

·         Unary logical operation: NOT

1.     && (AND) – It is used to check if both the operands are true.

2.     || (OR) – These operators are used to check if at least one of the operand is true.

3.     ! (NOT) – Used to check if the operand is false

If the logical statement is satisfied (it is true), then the program will return the value 1, otherwise, if the relational statement is not satisfied (it is false), the program will return the value 0.

Table for Logical Operators in C and C++

Operator

Operand

Operation

Elucidation

&&

a, b

(a && b)

AND: Used to check if both the operands are true

||

a, b

(a || b)

OR: Used to check if at least one of the operand is true

!

a

!a

NOT: Used to check if the operand is false

Assignment Operators

It is used to assign a particular value to a variable. We will discuss it in detail in the later section with its shorthand notations.

1.     =  (Assignment)- Used to assign a value from right side operand to left side operand.

2.     += (Addition Assignment)- To store the sum of both the operands to the left side operand.

3.     -= (Subtraction Assignment) – To store the difference of both the operands to the left side operand.

4.     *= (Multiplication Assignment) – To store the product of both the operands to the left side operand.

5.     /= (Division Assignment) – To store the division of both the operands to the left side operand.

6.     %= (Remainder Assignment) – To store the remainder of both the operands to the left side operand.

Table for Assignment Operators in C and C++

Operator

Operand

Operation

Elucidation

=

a, b

a=b

Used to assign a value from right side operand to left side operand

+=

a, b

a+=b

a=a+b: The value of a+b is stored in a

-=

a, b

a-=b

a=a-b: The value of a-b is stored in a

*=

a, b

a*=b

a=a*b: The value of a*b is stored in a

/=

a, b

a/=b

a=a/b: The value of a/b is stored in a

%=

a, b

a%=b

a=a %b: The value of a%b is stored in a

Bitwise Operators

It is based on the principle of performing operations bit by bit which is based on boolean algebra. It increases the processing speed and hence the efficiency of the program.

The Bitwise Operators in C++ Includes –

1.     & (Bitwise AND) – Converts the value of both the operands into binary form and performs AND operation bit by bit.

2.     | (Bitwise OR) – Converts the value of both the operands into binary form and performs OR operation bit by bit.

3.     ^ (Bitwise exclusive OR) – Converts the value of both the operands into binary form and performs EXCLUSIVE OR operation bit by bit.

4.     ~ (One’s complement operator): Converts the operand into its complementary form.

5.     << – Left shift

6.     >> – Right shift

In order to clearly understand bitwise operators, let us see the truth table for various bitwise operations and understand how it is associated with boolean algebra.

Since there are 2 variables, namely, a and b, there are 22 combinations for values a and b can take simultaneously.

AND – Both the operands should have boolean value 1 for the result to be 1.

OR – At least one operand should have boolean value 1 for the result to be 1.

XOR (EXCLUSIVE OR) – Either the first operand should have boolean value 1 or the second operand should have boolean value 1. Both cannot have the boolean value 1 simultaneously.

One Complement: iF

a

b

a & b

a | b

a ^ b

~a

0

0

0

0

0

1

0

1

0

1

1

1

1

0

0

1

1

0

1

1

1

1

0

0

The left and right shift operators are responsible for shifting the binary values by some specific number of places.

Left shift: It specifies the value of the left operand to be shifted to the left by the number of bits specified by its right operand

Right shift: It species the value of the left operand to be shifted to the right by the number of bits specified by its right operand.

Let us take an example each of performing bitwise AND, OR, EXCLUSIVE OR and ONE’S COMPLEMENT operation.

Table for Bitwise Operators in C++

Operator

Operand

Operation

Elucidation

&

a, b

( a & b )

Bitwise AND: Converts the value of both the operands into binary form and performs AND- operation bit by bit

|

a, b

( a | b )

Bitwise OR:
Converts the value of both the operands into binary form and performs OR- operation bit by bit

^

a, b

( a ^ b )

Bitwise exclusive OR: Converts the value of both the operands into binary form and performs EXCLUSIVE OR operation bit by bit

~

a

( ~ a )

One’s complement operator: Converts the operand into its complementary form

<< 

a

a<<

Left shift

>> 

a

a>>

Right shift

Miscellaneous Operators

Here is a table which illustrates the use of these operators:

1.     sizeof – It returns the memory occupied by the particular data type of the operand

2.     & (Pointer) – It refers to the address (memory location) in which the operand is stored.

3.     *  (Pointer) –  It is a pointer operator

4.     ? (Condition) – It is an alternative for if-else condition

A table for Misc Operators in C++

Operator

Operand

Operation

Elucidation

sizeof

a

sizeof(a)

It returns the memory occupied by the particular data type of the operand

&

a

& a

It refers to the address (memory location) in which the operand is stored.

*

a

* a

It is a pointer

?:

a,b

a?b:     

It is an alternative for if-else condition statement

Variables in C++

A variable is a storage space associated with a unique name to identify them. When we want to store some data on our system in the computer memory, is it possible for me to be able to remember these memory addresses? The answer is no, and that is the reason why we use variables.

Variables in C++ programming help us to store values depending upon the size of the variable. With the help of variables, we can decide what amount and type of data store in a variable. When you assign a data type and name to some space in the memory, variables are defined.

Variables reserve some memory in the storage space, that you can access later in the program. By declaring a variable, you inform the operating system to reserve memory indicated by some name. i.e. variable_name.

Naming a Variable in C ++

You need to follow some rules, before naming a variable in C and C++:

1.     A variable must not start with a digit.

2.     A variable can begin with an alphabet or an underscore.

3.     Variables in C and C++ are case-sensitive which means that uppercase and lowercase characters are treated differently.

4.     A variable must not contain any special character or symbol.

5.     White spaces are not allowed while naming a variable.

6.     Variables should not be of the same name in the same scope.

7.     A variable name cannot be a keyword.

8.     The name of the variable should be unique.

Let’s see some examples of both valid and invalid variable names.

Valid variable names

ticketdata
_ticketdata
ticket_data

Invalid variable names

56ticketdata
ticket@data
ticket data

Variable Definition

A variable definition in C and C++ defines the variable name and assigns the data type associated with it in some space in computer memory. After giving its definition, this variable can be used in the program depending upon the scope of that variable.

By defining a variable, you indicate the name and data type of the variable to the compiler. The compiler allocates some memory to the variable according to its size specification.

Rules for Defining Variables in C and C++

1.     Must contain data_type of that variable.

Example:

Int     start;
float  width;
char   choice;

 

2.     The variable name should follow all the rules of the naming convention.

3.     After defining the variable, terminate the statement with a semicolon otherwise it will generate a termination error. Example: int sum;

4.     The variable with the same data type can work with a single line definition. Example: float height, width, length;

 

Defining Variables in C++ with Example

int var;

Here, a variable of integer type with the variable name var is defined. This variable definition allocates memory in the system for var.

Another example,

char choice ;

When we define this variable named choice, it allocates memory in the storage space according to the type of data type in C, i.e., character type.

Variable Declaration

There is a huge difference between defining a variable and declaring a variable.

By declaring a variable in C++, we simply tell the compiler that this variable exists somewhere in the program. But, the declaration does not allocate any memory for that variable.

Declaration of variable informs the compiler that some variable of a specific type and name exists. The definition of variable allocates memory for that variable in the program.

So, it is safe to say that the variable definition is a combination of declaration and memory allocation. A variable declaration can occur many times but variable definition occurs only once in a program, or else it would lead to wastage of memory.

Variable Initialization

Variable initialization means assigning some value to that variable. The initialization of a variable and declaration can occur in the same line.

1.     int demo = 23;

By this, we initialize the variable demo for later use in the program.

Data Types in C and C++

A programming language cannot work without a wide range of data types as each type has its own significance and utility to perform various tasks. Here, reasons are mentioned why we require different data types in C and C++ Programming:

·         At the time of the variable declaration, it becomes convenient for the user to distinguish which type of data variable stores.

·         It makes it clear for the user to identify the return value of the function based on the data type.

·         If parameters are passed to the function, it becomes easy for the user to give input according to the given format.

This is just the beginning, at the end of this article, you will be an expert in Data

  Types of Data Types in C++

Primary Data Types in C++

·         int: It is responsible for storing integers. The memory it occupies depends on the compiler (32 or 64 bit). In general, int data type occupies 4 bytes of memory when working with a 32-bit compiler.

·         float: It is responsible for storing fractions or digits up to 7 decimal places. It is usually referred to as a single-precision floating-point type. It occupies 4 bytes of memory

·         char: It can be used to store a set of all characters which may include alphabets, numbers and special characters. It occupies 1 byte of memory being the smallest addressable unit of a machine containing a fundamental character set.

·         double: It is responsible for storing fractions or digits up to 15-16 decimal places. It is usually referred to as a double-precision floating-point type.

·         void (Null) data type: It indicates zero or no return value. It is generally used to assign the null value while declaring a function.

There are few more data types available in the C++ programming language.

They are:

·         bool: It refers to a boolean/logical value. It can either be true or false.

·         wchar_t: It refers to a wide character whose size is either 2 or 4 bytes. It is similar to the char data type but the only difference is the space occupied in the computer memory.

·         string: Instead of declaring an array of characters to enter a string data type, C++ gives you the provision to declare the “string” data type.

Along with data types, comes modifiers. Modifiers basically alter the function of a data type and make it more specific by the inclusion of additional provisions. These include:

·         Signed: It is used to store zero, positive or negative values.

·         Unsigned: It can store only zero or positive values.

·         Long:  It is used to store large integer numbers. The size of the long type is 8 bytes.

·         Short: It is used to store small integer numbers. Its size is of 2 Bytes.

Secondary (Derived) Data Types in C and C++

As the name itself suggests, they are derived from the fundamental data types in the form of a group to collect a cluster of data used as a single unit. These include:

·         Arrays: A collection of data items of similar data types, which is accessed using a common name.

The basic syntax of declaring an array is:

 return_type array_name[size]];

For instance: float marks[5];

·         Pointers: Pointers in C++ is basically variables that are used to store the memory address of another variable.

·         Functions: It is a group of statements that are written to perform a specific task. Functions are either user-defined or built-in library functions.

User-defined Data Types in C++

·         Structures – It is a user-defined data type in which a collection of different data types can be made and accessed through an object.

·         Union– A special kind of data type which gives us the provision to store different data types in the same memory location.

·         Enumeration – It refers to the arithmetic data types used to define variables to specify only certain discrete integer values throughout the entire program.


Manipulators

Manipulators are operators used in C++ for formatting output. The data is manipulated by the programmer's choice of display.

Some of the more commonly used manipulators are given below:

1.           1. endl Manipulator

       2.  setw Manipulator

       3. setfill Manipulator

endl Manipulators:

endl  is the line feed operator in C++. It acts as a stream manipulator whose purpose is to feed the whole line and then point the cursor to the beginning of the next line. We can use \n (\n is an escape sequence) instead of endl for the same purpose.

Setw Manipulators:

This manipulator sets the minimum field width on output.

Syntax:

                        setw(x)

#include <iostream>

#include <iomanip>

using namespace std;

 int main() {

 float basic, ta,da,gs;

basic=10000; ta=800; da=5000;

gs=basic+ta+da;

cout<<setw(10)<<"Basic"<<setw(10)<<basic<<endl

<<setw(10)<<"TA"<<setw(10)<<ta<<endl

<<setw(10)<<"DA"<<setw(10)<<da<<endl

<<setw(10)<<"GS"<<setw(10)<<gs<<endl;

return 0;

}

Setfill Manipulator:

This is used by the setw manipulator. If a value does not entirely fill a field, then the character specified in the setfill argument of the manipulator is used for filling the fields.

/#include <iostream>

#include <iomanip>

using namespace std;

 int main() {

cout << setw(20) << setfill('*') << "w3schools.in" << setw(20) << setfill('*')<<"Test"<< endl;

}

                 C++ Expressions

C++ expression consists of operators, constants, and variables which are arranged according to the rules of the language. It can also contain function calls which return values. An expression can consist of one or more operands, zero or more operators to compute a value. Every expression produces some value which is assigned to the variable with the help of an assignment operator.

Expression can be of following types:

  • Constant expressions
  • Integral expressions
  • Float expressions
  • Pointer expressions
  • Relational expressions
  • Logical expressions
  • Bitwise expressions

Constant expressions

A constant expression is an expression that consists of only constant values. It is an

expression whose value is determined at the compile-time but evaluated at the run-time

#include <iostream> 

using namespace std; 

int main() 

    int x;        // variable declaration. 

    x=(3/2) + 2;  // constant expression 

    cout<<"Value of x is : "<<x;  // displaying the value of x. 

    return 0; 

In the above code, we have first declared the 'x' variable of integer type. After declaration, we assign the simple constant expression to the 'x' variable.

Output

Value of x is : 3  
 

Integral Expressions

An integer expression is an expression that produces the integer value as output after performing all the explicit and implicit conversions.

#include <iostream> 

using namespace std; 

int main() 

    int x;  // variable declaration. 

    int y;  // variable declaration 

    int z;  // variable declaration 

    cout<<"Enter the values of x and y"; 

    cin>>x>>y; 

    z=x+y; 

    cout<<"\n"<<"Value of z is :"<<z; //  displaying the value of z. 

    return 0; 

In the above code, we have declared three variables, i.e., x, y, and z. After declaration, we take the user input for the values of 'x' and 'y'. Then, we add the values of 'x' and 'y' and stores their result in 'z' variable.

 Output

 Enter the values of x and y                                                                                                     

8                                                                                                                              

9                                                                                                                               

Value of z is :17 

 Float Expressions

A float expression is an expression that produces floating-point value as output after performing all the explicit and implicit conversions.

#include <iostream> 

using namespace std; 

int main() 

    float x=8.9;      // variable initialization 

   float y=5.6;      // variable initialization 

   float z;             // variable declaration 

   z=x+y; 

   std::cout <<"value of z is :"  << z<<std::endl;  // displaying the value of z. 

      return 0; 

Output

 value of z is :14.5

  Pointer Expressions

A pointer expression is an expression that produces address value as an output.  

#include <iostream> 

using namespace std; 

int main() 

   int a[]={1,2,3,4,5};  // array initialization 

   int *ptr;       // pointer declaration 

   ptr=a;    // assigning base address of array to the pointer ptr 

   ptr=ptr+1;   // incrementing the value of pointer 

   std::cout <<"value of second element of an array : "  << *ptr<<std::endl; 

   return 0; 

In the above code, we declare the array and a pointer ptr. We assign the base address to the variable 'ptr'. After assigning the address, we increment the value of pointer 'ptr'. When pointer is incremented then 'ptr' will be pointing to the second element of the array.

 Output

 value of second element of an array : 2

Relational Expressions

A relational expression is an expression that produces a value of type bool, which can be either true or false. It is also known as a boolean expression. When arithmetic expressions are used on both sides of the relational operator, arithmetic expressions are evaluated first, and then their results are compared.

#include <iostream> 

using namespace std; 

int main() 

    int a=45;    // variable declaration 

    int b=78;    // variable declaration 

    bool y= a>b;   // relational expression 

    cout<<"Value of y is :"<<y;  // displaying the value of y. 

    return 0; 

In the above code, we have declared two variables, i.e., 'a' and 'b'. After declaration, we have applied the relational operator between the variables to check whether 'a' is greater than 'b' or not.

 Output

 Value of y is :0

Logical Expressions

A logical expression is an expression that combines two or more relational expressions and produces a bool type value. The logical operators are '&&' and '||' that combines two or more relational expressions.

#include <iostream> 

using namespace std; 

int main() 

 int a=2; 

 int b=7; 

 int c=4; 

cout<<((a>b)||(a>c)); 

return 0; 

Output

0

Bitwise Expressions

A bitwise expression is an expression which is used to manipulate the data at a bit level. They are basically used to shift the bits.

For example:

x=3

x>>3 // This statement means that we are shifting the three-bit position to the right.

In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting the value of 'x' by three-bit position to the right. Let's understand through the diagrammatic representation.

Control Structures in C++

Control structures form the basic entities of a “structured programming language“.Control structures are used to alter the flow of execution of the program.

There are three types of control structures available in C++

1) Sequence structure (straight line paths)

2) Selection structure (one or many branches)

3) Loop structure (repetition of a set of activities)

 Sequence structure: Default mode. Sequential execution of code statements (one line after another)

             

                                

Selection structures:

Selection used for decisions, branching -- choosing between 2 or more alternative paths.

Selection structures are implemented C++ with If, If Else and Switch statements. If and If Else statements are 2 way branching statements where as Switch is a multi branching statement.

 

The simple If statement:

The syntax format of a simple if statement is as shown below.

if (expression)

{

statement 1;

statement 2;

}

statement 3;

The flow diagram of if statement is given:

 

The expression given inside the brackets after if is evaluated first. If the expression is true, then statements inside the curly braces that follow if(expression) will be executed. If the expression is false, the statements inside curly braces will not be executed and program control goes directly to statements after curly braces.

Example Program:

#include<iostream>

#include<conio.h>

int main()

{

     int a;

     cout<<"Enter the Number :";

     cin>>a;

         if(a > 10)

     {

        cout<<a<<" Is Greater than 10";

     }

      getch();

     return 0;

 }

 If –else Statement:

The basic format of if else statement is:

 

if(test_expression)

{

   //execute your code

}

else

{

   //execute your code

}

The flow diagram of if- else statement is given:

 

Example Program:

#include <iostream>

int main()

{

  int a = 15, b = 20;

  if (b > a)

  { 

    cout << "b is greater" << endl;

  }

else

 { 

    cout << "a is greater" << endl;

  } 

}

Switch Statement:

The basic format of switch statement is:

                 switch(variable)

{

case 1:

   //execute your code

break;

 

case n:

   //execute your code

break;

 

default:

   //execute your code

break;

}

After the end of each block it is necessary to insert a break statement because if the programmers do not use the break statement, all consecutive blocks of codes will get executed from each and every case onwards after matching the case block.

The flow diagram of switch statement is given:

 

  Example program

     #include <iostream>

main()

{

    int a;

    cout << "Please enter a no between 1 and 5: " << endl; cin >> a;

      switch(a)

    {

    case 1:

    cout << "You chose One" << endl;

    break;

   

    case 2:

    cout << "You chose Two" << endl;

    break;

 

    case 3:

    cout << "You chose Three" << endl;

    break;

 

    case 4:

    cout << "You chose Four" << endl;

    break;

 

    case 5:

    cout << "You chose Five" << endl;

    break;

 

    default :

    cout << "Invalid Choice. Enter a no between 1 and 5" << endl;

    break;

    }

}

 Loops structure:

Sometimes it is necessary for the program to execute the statement several times, and C++ loops execute a block of commands a specified number of times until a condition is met

C++ supports following types of loops:

while loops

do while loops

for loops

 

While loop:

while loop is a most basic loop in C++. while loop has one control condition, and executes as long the condition is true.  The condition of the loop is tested before the body of the loop is executed, hence it is called an entry-controlled loop.

 The basic format of while loop statement is:

         While (condition)

{

   statement(s);

   Incrementation;

}

Flowchart of while loop:

             

Example program

#include <iostream>

int main ()

{

    int n = 1,times=5;

    while( n <= times )

   {

      cout << "C++ while loops: " << n <<endl;

      n++;

   }

   return 0;

}

 do-while loop:

C++ do while loops are very similar to the while loops, but it always executes the code block at least once and furthermore as long as the condition remains true. This is an exit-controlled loop.

The basic format of do while loop statement is:

         do

{

   statement(s);

 

}while( condition );

Flowchart of do while loop:

              

 Example program:

#include <iostream>

using namespace std;

 int main ()

{

     int n = 1,times=0;

    do

   {

      cout << "C++ do while loops: " << n <<endl;

      n++;

   }while( n <= times );

   return 0;

}

for loops:

C++ for loops is very similar to a while loops in that it continues to process a block of code until a statement becomes false, and everything is defined in a single line. for loop is an entry-controlled loop.

The basic format of for loop statement is:

                     for ( init; condition; increment )

{

   statement(s);

}

Flowchart of for loop:

          

Example program

#include <iostream>

int main ()

{

int n = 1,times=5;

 

for( n = 1; n <= times; n++  )

   {

      cout << "C++ for loops: " << n <<endl;

   }

   return 0;

}

Function

A function is a set of statements that are put together to perform a specific task.

There are many advantages of functions.

 1) Code Reusability

 By creating functions in C++, you can call it many times. So we don't need to write the same code again and again.

 2) Code optimization

 It makes the code optimized, we don't need to write much code.

 Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

 But if you use functions, you need to write the logic only once and you can reuse it several times.

Types of Functions

There are two types of functions in C programming:

 1. Built in functions or Library Functions: are the functions which are declared in the C++ header files such as sin(x), cos(x), exp(x), etc.

 2. User-defined functions: are the functions which are created by the C++ programmer, so that he/she can use it many times. It reduces complexity of a big program and optimizes the code.

                     

User Defined Functions

C++ also allows its users to define their own functions. These are the user-defined functions. We can define the functions anywhere in the program and then call these functions from any part of the code. Just like variables, it should be declared before using, functions also need to be declared before they are called.

 The general syntax for user-defined functions (or simply functions) is as given below:

     return_type functionName(param1,param2,….param3)

{

Function body;

}

each function has:

 Return type: It is the value that the functions return to the calling function after performing a specific task.

functionName : Identifier used to name a function.

Parameter List: Denoted by param1, param2,…paramn in the above syntax. These are the arguments that are passed to the function when a function call is made. The parameter list is optional i.e. we can have functions that have no parameters.

Function body: A group of statements that carry out a specific task.

As already mentioned, we need to ‘declare’ a function before using it.

 Function Declaration

A function declaration tells the compiler about the return type of function, the number of parameters used by the function and its data types. Including the names of the parameters in the function, the declaration is optional. The function declaration is also called as a function prototype.

         int sum(int, int);

Above declaration is of a function ‘sum’ that takes two integers as parameters and returns an integer value.

         void swap(int, int);

This means that the swap function takes two parameters of type int and does not return any value and hence the return type is void.

         void display();

The function display does not take any parameters and also does not return any type.

 Function Definition

A function definition contains everything that a function declaration contains and additionally it also contains the body of the function enclosed in braces ({}).

 In addition, it should also have named parameters. When the function is called, control of the program passes to the function definition so that the function code can be executed. When execution of the function is finished, the control passes back to the point where the function was called.

 For the above declaration of swap function, the definition is as given below:

 void swap(int a, int b)

{

b = a + b;

a = b - a;

b = b - a;

}

Note that declaration and definition of a function can go together. If we define a function before referencing it then there is no need for a separate declaration.

 Let us take a complete programming Example to demonstrate a function.

 #include <iostream>

using namespace std;

 void swap(int a, int b)

{           //here a and b are formal parameters

b = a + b;

a = b - a;

b = b - a;

cout<<"\nAfter swapping: ";

cout<<"a = "<<a;

cout<<"\tb = "<<b;

return;

}

int main()

{

int a,b;

cout<<"Enter the two numbers to be swapped: "; cin>>a>>b;

 

cout<<"a = "<<a;

cout<<"\tb = "<<b;

swap(a,b);           //here a and b are actual parameters

}

Output:

 Enter the two numbers to be swapped: 5 3

a = 5 b = 3

After swapping: a = 3 b = 5

     In the above example, we see that there is a function swap that takes two parameters of type int and returns nothing. Its return type is void. As we have defined this function before function main, which is a calling function, we have not declared it separately.

     In the function main, we read two integers and then call the swap function by passing these two integers to it. In the swap function, the two integers are exchanged using a standard logic and the swapped values are printed.

Passing Parameters To Functions

 Call by value and call by reference

·        In call by value, value of the argument is passed during function calling. In call by reference address of the argument is passed during function calling.

·        In call by value of actual arguments do not changes. But in call by reference value of actual argument changes.

·        Memory can be saved if we call a function by reference.

Call by value

#include <iostream.h>

void swap (int x, int y)

 {

int temp;

temp = x;

 x = y;

 y = temp;

}

int main()

 {

  int x=500, y=100;    

 swap(x, y);  // passing value to function  

 cout<<"Value of x is: "<<x<<endl;  

 cout<<"Value of y is: "<<y<<endl;  

 return 0;  

}

 Output:

Value of x is: 500 Value of y is: 100

 Call by reference:

#include<iostream.h>   

void swap(int *x, int *y)  

{  

 int swap;  

 swap=*x;  

 *x=*y;  

 *y=swap;  

}

int main()   

{    

 int x=500, y=100;    

 swap(&x, &y);  // passing value to function  

 cout<<"Value of x is: "<<x<<endl;  

 cout<<"Value of y is: "<<y<<endl;  

 return 0;  

}    

Output:

Value of x is: 100 Value of y is: 500

 

Difference between call by value and call by reference in C++

No.

              Call by value

                Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 POINTERS

The pointer is a one of the C++ programming language data-type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address.

 SYNTAX

Pointer variable = &variable;

 Example:

 #include <iostream.h>

int main()

{

int i=10;

int *ptr;

ptr=&i;

cout<<“value of i”<<i;

cout<<“address of i”<<i;

cout<<“value of ptr:”<<ptr;

cout<<“address of ptr:”<<&ptr;

cout<<“ptr’s pointer value”<<*ptr;

}

OUTPUT

value of i:10

address of i :ox6dfefc

value of ptr:ox6dfefc

address of ptr:ox6dfef8

ptr’s pointer value:10


Default Arguments in C++ Functions

The default arguments are used when you provide no arguments or only few arguments while calling a function. The default arguments are used during compilation of program.

For example, lets say you have a user-defined function sum declared like this: int sum(int a=10, int b=20),

now while calling this function you do not provide any arguments, simply called sum(); then in this case the result would be 30, compiler used the default values 10 and 20 declared in function signature. If you pass only one argument like this: sum(80) then the result would be 100, using the passed argument 80 as first value and 20 taken from the default argument.

 Example:

#include <iostream>

using namespace std;

int sum(int a, int b=10, int c=20);

 

int main()

  {

    cout<<sum(1)<<endl;

    cout<<sum(1, 2)<<endl;

    cout<<sum(1, 2, 3)<<endl;

   return 0;

}

int sum(int a, int b, int c){

   int z;

   z = a+b+c;

   return z;

}

 Output:

31

23

6


INLINE FUNCTION

C++ provides an inline functions to reduce the function call overhead. Inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call. This substitution is performed by the C++ compiler at compile time. Inline function may increase efficiency

if it is small.
The syntax for defining the function inline is:

inline return-type function-name(parameters) { // function code }

EXAMPLE:

#include <iostream>

using namespace std;

inline int cube(int s)

{

    return s*s*s;

}

int main()

{

    cout << "The cube of 3 is: " << cube(3) << "\n";

    return 0;

}

 Output: The cube of 3 is: 27

 Function overloading in C++

     Function Overloading is defined as the process of having two or more function with the same name, but different in parameters is known as function overloading in C++. In function overloading, the function is redefined by using either different types of arguments or a different number of arguments. It is only through these differences compiler can differentiate between the functions.

     The advantage of Function overloading is that it increases the readability of the program because you don't need to use different names for the same action.

Example:

#include<iostream> 

using namespace std; 

int mul(int,int); 

float mul(float,int); 

 int mul(int a,int b) 

    return a*b; 

float mul(double x, int y) 

    return x*y; 

int main() 

    int r1 = mul(6,7); 

    float r2 = mul(0.2,3);  

    std::cout << "r1 is : " <<r1<< std::endl; 

    std::cout <<"r2 is : "  <<r2<< std::endl; 

    return 0; 

Output:

 r1 is : 42

r2 is : 0.6 

Classes and Objects

The classes are the most important feature of C++ that leads to Object Oriented programming. Class is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating instance of that class.

 The variables inside class definition are called as data members and the functions are called member functions.

 For example: Class of birds, all birds can fly and they all have wings and beaks. So here flying is a behavior and wings and beaks are part of their characteristics. And there are many different birds in this class with different names but they all posses this behavior and characteristics.

     Similarly, class is just a blue print, which declares and defines characteristics and behavior, namely data members and member functions respectively.

Create a Class

To create a class, use the class keyword: objects of this class will share these characteristics and behavior.

Example

Create a class called "MyClass":

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

 Example explained

The class keyword is used to create a class called MyClass.

  • ·        The public keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class. You will learn more about access specifiers later.
  • ·        Inside the class, there is an integer variable myNum and a string variable myString. When variables are declared within a class, they are called attributes.
  • ·        At last, end the class definition with a semicolon ;.

·        Create an Object

·            In C++, an object is created from a class. We have already created the class named MyClass, so now we can use this to create objects.

 To create an object of MyClass, specify the class name, followed by the object name.

To access the class attributes (myNum and myString), use the dot syntax (.) on the object:

 Example

Create an object called "myObj" and access the attributes:

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  
// Create an object of MyClass

  
// Access attributes and set values
  myObj.myNum = 15
  myObj.myString = 
"Some text";

  
// Print attribute values
  cout << myObj.myNum << "\n";
  cout << myObj.myString;
  
return 0;
}

Multiple Objects

You can create multiple objects of one class:

Example

// Create a Car class with some attributes
class Car {
  
public:
    string brand;   
    string model;
    
int year;
};

int main() {
  
// Create an object of Car
  Car carObj1;
  carObj1.brand = 
"BMW";
  carObj1.model = 
"X5";
  carObj1.year = 
1999;

  
// Create another object of Car
  Car carObj2;
  carObj2.brand = 
"Ford";
  carObj2.model = 
"Mustang";
  carObj2.year = 
1969;

  
// Print attribute values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << 
" " << carObj2.model << " " << carObj2.year << "\n";
  
return 0;

}

Constructor

        A constructor is a special member function whose task is to initialize the object of a class.

  •      Its name is same as the class name.
  •     A constructor does not have a return type.
  •      A constructor is called or invoked when the object of its associated class is created.
  •     It is called constructor because it constructs the values of data members of the class.
  •     A constructor cannot be virtual (shall be discussed later on).
  •     A constructor can be overloaded.

There three types of constructor:

(i) Default Constructor

(ii) Parameterized Constructor

(iii) Copy constructor

Default Constructor

The constructor which has no arguments is known as default constructor.

Program:

#include<iostream.h>

class Add

{

int x, y, z;

public:

Add(); // Default Constructor

void calculate(void);

void display(void);

};

Add::Add()

{

x=6;

y=5;

}

void Add :: calculate()

{

z=x+y;

}

void Add :: display()

{

cout<<z;

}

void main()

{

Add a;

a.calculate();

a.display();

}

 Output:

11

Parameterized constructor

The constructor which takes some argument is known as parameterized constructor.

Program:

#include<iostream.h>

class Add

{

int x, y, z;

public:

Add(int, int);

void calculate(void);

void display(void);

};

Add :: Add(int a, int b)

{

x=a;

y=b;

}

void Add :: calculate()

{

z=x+y;

}

void Add :: display()

{

cout<<z;

}

void main()

{

Add a(5, 6);

a.calculate();

a.display();

}

 Output:

11

Copy Constructor

The constructor which takes reference to its own class as argument is known as copy constructor.

Program:

#include<iostream.h>

class Add

{

int x, y, z;

public:

Add()

 {

 }

Add(int a, int b)

{

x=a;

y=b;

}

Add(Add &);

void calculate(void);

void display(void);

};

Add :: Add(Add &p)

{

 x=p.x;

y=p.y;

cout<<”Value of x and y for new object: ”<<x<<” and ”<<y<<endl;

}

void Add :: calculate()

{

z=x+y;

}

void Add :: display()

{

cout<<z;

}

void main()

{

Add a(5, 6);

Add b(a);

b.calculate();

b.display();

}

Output:

Value of x and y for new object are 5 and 6

11

Destructor

  •      It is a special member function which is executed automatically when an object is destroyed.
  •          Its name is same as class name but it should be preceded by the symbol ~.
  •          It cannot be overloaded as it takes no argument.
  •          It is used to delete the memory space occupied by an object.
  •          It has no return type.
  •          It should be declared in the public section of the class.

 Program:

#include<iostream.h>

class XYZ

{

int x;

public:

XYZ( );

~XYZ( );

void display(void);

};

XYZ::XYZ( )

{

x=9;

}

XYZ:: ~XYZ( )

{

cout<<”Object is destroyed”<<endl;

}

void XYZ::display()

{

cout<<x;

}

void main()

{

XYZ xyz;

xyz.display();

}

 

Output:

9

Friend Function

·        Scope of a friend function is not inside the class in which it is declared.

·         Since its scope is not inside the class, it cannot be called using the object of that class

·         It can be called like a normal function without using any object.

·         It cannot directly access the data members like other member function and it can access the

·        data members by using object through dot operator.

·         It can be declared either in private or public part of the class definition.

·         Usually it has the objects as arguments.

 

Program:

#include<iostream.h>

class Add

{

int x, y, z;

public:

Add(int, int);

friend int calculate(Add p);

};

Add :: Add(int a, int b)

{

x=a;

y=b;

}

int calculate(Add p)

{

return(p.x+p.y);

}

void main()

{

Add a(5, 6);

cout<<calculate(a);

}

 

Output:

11


Friend Classes

It is possible for one class to be a friend of another class. When this is the case, the friend class and all of its member functions have access to the private members defined within the other class.

Program:

#include<iostream.h>

          class Rectangle

          {

                   int L,B;

                   public:

                   Rectangle()

                   {

                             L=10;

                             B=20;

                   }

                   friend class Square;        //Statement 1

          };

          class Square

          {

                   int S;

                   public:

                   Square()

                   {

                             S=5;

                   }

                   void Display(Rectangle Rect)

                   {

                             cout<<"\n\n\tLength : "<<Rect.L;

                             cout<<"\n\n\tBreadth : "<<Rect.B;

                             cout<<"\n\n\tSide : "<<S;

                   }

          };

          void main()

          {

 

                   Rectangle R;

                   Square S;

                   S.Display(R);       //Statement 2

          }

          Output :

                    Length : 10

                     Breadth : 20

                     Side : 5

 

Type Conversion in C++

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 ->

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:

#include <iostream>

int main()

{

    int x = 10; // integer x

    char y = 'a'; // character c

     x = x + y;

     float z = x + 1.0;

     cout << "x = " << x << endl

            << "y = " << y << endl

           << "z = " << z << endl;

      return 0;

}

Output:

x = 107

y = a

z = 108.0

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.

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.

#include <iostream>

int main()

{

    double x = 1.2;

    int sum = (int)x + 1;

    cout << "Sum = " << sum;

   return 0;

}

Output:

Sum = 2

C++ Operators Overloading

Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.

The advantage of Operators overloading is to perform different operations on the same operand.

Operator that cannot be overloaded are as follows:

·        Scope operator (::)

·        Sizeof

·        member selector(.)

·        member pointer selector(*)

·        ternary operator(?:)

Syntax of Operator Overloading

return_type class_name  : : operator op(argument_list) 

     // body of the function. 

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being overloaded, and the operator is the keyword.

Rules for Operator Overloading

  •     Existing operators can only be overloaded, but the new operators cannot be overloaded.
  •         The overloaded operator contains atleast one operand of the user-defined data type.
  •         We cannot use friend function to overload certain operators. However, the member function can be used to overload those operators.
  •         When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument.
  •         When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments.

C++ Operators Overloading Example

Let's see the simple example of operator overloading in C++.

// program to overload the unary operator ++.

#include <iostream>   

using namespace std;   

class Test   

{   

   private:   

      int num;   

   public:   

       Test(): num(8){}   

       void operator ++()  

  {    

          num = num+2;    

  }   

       void Print() {    

           cout<<"The Count is: "<<num;    

    }   

};   

int main()   

{   

    Test tt;   

    ++tt;  // calling of a function "void operator ++()"   

    tt.Print();   

    return 0;   

}   

Output:

 The Count is: 10

Let's see a simple example of overloading the binary operators.

// program to overload the binary operators.

#include <iostream> 

using namespace std; 

class A 

     int x; 

      public: 

      A(){} 

    A(int i) 

    { 

       x=i; 

    } 

    void operator+(A); 

    void display(); 

}; 

 

void A :: operator+(A a) 

    int m = x+a.x; 

    cout<<"The result of the addition of two objects is : "<<m; 

 } 

int main() 

    A a1(5); 

    A a2(4); 

    a1+a2; 

    return 0; 

Output:

The result of the addition of two objects is : 9


 

 

 

No comments:

Post a Comment