C++ Programming Language

Class Notes of C++

What is C ++ Programming Language?

In 1972, Dennis Ritchie developed a new language called 'C'. Different versions of C language were introduced that were implemented on different systems. C was a compiler based high-level language. However, it was used for low level programming also.

C had its own features advantages yet it had some weaknesses limitations/drawbacks. For example, it had poor code reusability and had no GUI interface etc.

To reduce the limitations of C and to add some addition, features/facilities, and developed a language called C++. So, C++ is an incremented version of C. In 1985, at first time C++ was commercially available in the market.

C++ is an object oriented programming language. It has its own features/characteristics such as polymorphism, encapsulation, abstraction, inheritance, templates, classes and objects, and exception handling. It may be noted that C++ is not a pure object oriented programming language. It is al hybrid language, because you can write programs in it in a C style also.

Objected Oriented Programming Language

In object Oriented Programming (OOP), a program is not only divided to functions and structures but also to classes and objects. A class/object is the combination of data and functions in to a single unit.

Combining the data and functions in such a way is called capsulation. The data within an object/class is called data member whereas the functions within an object/class arecalled member functions. The data member is kept hidden from the outside. It is accessed through member functions the data is safe. A program may contain as many objects/classes as needed. Object Oriented Programming simplifies writing understanding, debugging and maintaining a huge program. It also models the real world things very well.

Structured Programming VS OOP i. In structured programming a program is divided in to functions and structures whereas in OOP a program may be divided in to classes and objects in addition to functions and structures.

Features/Characteristics of OOP Object Oriented Programming:

Object Oriented Programming (OOP) has many features or characteristics. Some common features of OOP are;

writing ram. It

1- Classes

2- Object

3-Inheritance

  1. Code re-usability

5.Polimorphism

6- Encapsulation and data hiding

7- Creating new data types.

1- Classes:

These 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 main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types.

A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

2-Objects:

A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box −

Box Box1; // Declare Box1 of type Box

Box Box2; // Declare Box2 of type Box

3-Inheritance:

 Inheritance is the process in which new classes can be derived/created from the existing classes. The newly created class is called child class or derived class or sub-class whereas the existing class is called base class or parent class or super class. The child class inherits the characteristics of the parent class or parent classes. The child classes may also have their own additional characteristics that differentiate them from the parent class, or one child class from another. For example we have a base class named “computers' which has properties like 'execution speed, ‘HDD', 'price' etc. The two child classes that can be derived from it may be 'laptop and 'desktop'. The child classes now have all the features of the base class, and may have their additional properties/features. For example a laptop may have additional properties such as Bluetooth and web camera. The main advantage of inheritance is code re-usability and to save programmer's time.

4-Code Reusability:

Code reusability means use a piece of code again and again without rewriting it. In OOP, code re-usability is achieved through inheritance. Using inheritance, you write code for a base class and then drive more classes from it without rewriting the code for derived classes. However, you have to write code for additional features of the derived classes. Another way to achieve code reusability is using functions.

4-Polymorphism:

Poly means "more than one and morphs mean “shapes or forms. So, Polymorphism means one thing with many forms. In OOP, Polymorphism is the ability or phenomenon to use an operator or function in different ways in addition to its normal usage. Thus Polymorphism gives different meanings or functionality to operators and functions.

5-Encapsulation:

In OOP Encapsulation is the process of combining data and functions into a single unit called object/class. Encapsulation leads to another important concept called data hiding. Data hiding means to hide the data members from the outside. Using encapsulation and data hiding one can't access the data directly. It can be accessed through member functions. So, encapsulation and data hiding provides security to data so that it is safe from outside interference and misuse.

 6- Creating New Data Types:

OOP provides the facility to create new data types i.e. one can create data types which is not already available. These data types are called user-defined data types. For example, suppose you want to store a complex number in computer memory. There is no way in procedural paradigm to store such a value. However, in OOP you can do so by defining a class named 'complex_no' and then creating objects of instance variables of that class. Similarly, we can store and subtract two dates using the concept of classes and objects.

 

Input / Output Statements

Formatted Input/Output

printf() and scanf() functions are inbuilt library functions in C programming language. 'Printf and Scanf function are used for formatted INPUT and OUTPUT.

We have to include “stdio.h” file use of these printf() and scanf() in C++ language.

Printf Function:

Printf allows formatted out put of data. In C programming language, printf() function is used to print the “character, string, float, integer, octal and hexadecimal values” onto the output screen. Its arguments are:

  1. It has some constant value for example “String Constant”.
  2. It has some control string, which controls what gets printed.
  3. Control string followed by a list of values to be substituted for entries in the control string.

 

Syntax:

Printf(“Control string / string constant ", List of argument)

Scanf Function: -

scanf allows formatted reading of data from the keyboard In C programming language, scanf() function is used to read character, string, numeric data from keyboard .

  1. It has some control string, which controls what gets printed.
  2. Control string followed by &variable name into which the typed response will be placed.

Syntax:

Scanf("control string ",&variable 1 ,&variablc2,,,,,,)

Standard output (cout)

On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.

For formatted output operations, cout is used together with the insertion operator, which is written as << (i.e., two "less than" signs).

cout << "Output sentence"; // prints Output sentence on screen

cout << 120; // prints number 120 on screen

cout << x; // prints variable value on the csreen

Multiple insertion operations (<<) may be chained in a single statement:

cout << "This " << " is a " << "single C++ statement";


Standard input (cin)

In most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin.

For formatted input operations, cin is used together with the extraction operator, which is written as >> (i.e., two "greater than" signs). This operator is then followed by the variable where the extracted data is stored. For example:

int age;

cin >> age;

endl function:

Alternatively, the endl manipulator can also be used to break lines. For example:

cout << "First sentence." << endl;

cout << "Second sentence." << endl;

getline() :-

This function is used to store a stream of characters as entered by the user in the object memory.

getline(cin,x);

gets( ) function:

The gets function is used to read a single line (until new line is encountered). When all input is finished (when enter key is pressed) a NULL character is append at the end of the string, which shows end of the string input.

Syntax:

gets (variable 1, variable2...) Where variable is any string type variable

 

puts () Function:

This function is used to print the string values on screen. When output of string is over, then a new line is inserted automatically.

 Syntax:

puts(variable name or string constant)

getch () Function:

Getch stand for "Get character ". This function is used to get the single character From the user during the execution of program. When we input the character then its not display on the screen and control is transfer to next statement without pressing enter key.

Syntax:

getch () Function:

getche () Function:

This function also gets the character form the user at time of execution. When we use getch then entered character not display on the screen but with getch character display on the screen and pressing of enter key is required.

Syntax:

getche () Function:

For example

X= getche();

When user enter the character then this character store in x (where x is a character variable).

Defining Constants

In C/C++ program we can define constants in two ways as shown below:

  1. Using #define preprocessor directive
  2. Using a const keyword
  1. Using #define preprocessor directive:

Preprocessor Directive are the lines included in program with the character# which make them different from the normal code. We can use this to declare a constant as shown below:

#define identifierName value

identifierName: It is the name given to constant.

value: This refers to any value assigned to identifierName.

Example:

#define val 10 

#define floatVal 4.5 

#define charVal 'G' 

  1. using a const keyword:

Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword.

Example:

For const int intVal = 10; 

Literals:

The values assigned to each constant variable are referred to as the literals. Generally, terms, constants and literals are used interchangeably.

 For example

 “const int = 5;“

 Is a constant expression and the value 5 is referred to as constant integer literal.

Data type on C/C++ language

There are two basic data types use in C/C++ language:

  1. Primary data types
  2. Derived data types

Primary data types:

These are fundamental data types in C/C++ namely integer(int), floating point(float), character(char) and void.

Derived data types:

Derived data types are nothing but primary data types but a little twisted or grouped together like array, structure, union and pointer. These are discussed in details later.

Primary Data Types:

1) Integer Data type: -

An integer data type is used to store the whole number. There are 3 types of integer’s namely decimal integer, octal integers and hexadecimal integer.

 

Decimal Integers: it consists of a set of digits 0 to 9 preceded by an optional + or - sign. Spaces, commas and non-digit characters are not permitted between digits. Example Decimal integer constants are

123 , -31 , 0 , 562321 , + 78

Some examples for invalid integer values are

15 750 , 20,000 , Rs. 1000

Octal Integers constant consists of any combination of digits from 0 through 7 with a O at the beginning. Some examples of octal integers are

O26 , O , O347 , O676

Hexadecimal integer constant is preceded by OX or Ox, they may contain alphabets from A to F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits. Example of valid hexadecimal integers are

OX2 , OX8C , Oxbcd , Ox

 2) Floating Point Data Type:

Floating Point data type is used to store the fractional part (Real Number).

Example of real values are:

0.0026 , -0.97 , 435.29 , +487.0

Floating Point Data type consist on Float, Double and Long Double

 

3) Character Data Type :

It is used to store a Single Character.

Example for character constants are

'5' , 'x' , ';' , ' '

Void type

void type means no value. This is usually used to specify the type of functions which returns nothing. We will get acquainted to this data type as we start learning more advanced topics in C language, like functions, pointers etc.

Preprocessor Directive

Preprocessor Directive are the lines included in program with the character# which make them different from the normal code.

processor directives are execute before compile actual program. with the help of

Preprocessor Directive we can include the header files in our program or define macro in our program.

Some of the Preprocessor Directive are:

#include<filename>

#define

#undefine

for example :

when we use getch() function then we must include conio.h file.

#include<conio.h>

Transfer OF Control

Control Structure:

In C program control is transfer form one statement to other statement in that order in which these statement are written. But some time we change this control according to our own need. For this purpose we use transfer of control statements.

 Two types of transfer of control are used in C++ Language:

  1. Conditional transfer of control
  2. Unconditional transfer of control

Conditional transfer of control:

In this type of control a condition is given. If the condition is true than control is transfer to specified statement. For this purpose we use Decision making statement (IF and else statement or switch statement).

IF Statement

if statement is decision making statement or decision control statement in this statement we give a condition after using “ IF “ key word. If the condition is “True “ then a statement or set of statements in the body of “ IF “ structure are executed and if the condition is "False” then nothing will be do and control is transfer to next statement according to sequences.

“ We say that if statement allows you to execute specific parts of a program if certain conditions are met (if condition is true) “.

If structure contain three main parts. The first is the keyword “ if “. The second is an expression enclosed in parentheses (Condition). The third is the block of code (which is written in parentheses) that you want to run if the condition met to given condition.

Syntax:

If (condition)

{ //Body of “ If “ Structure

statement 1;

statement 2;

}

IF-Else Statement

If-Else statement is decision making statement or decision control statement in this statement we use two Keyword “ IF “ and “ ELSE “ we give a condition after using “ IF “ key word. If the condition is “True “ then a statement or set of statements in the body of “ IF “ structure are executed and if the condition is "False” then statement or set of statement in the body of Else will be executed.

“ We say that if statement allows you to execute specific parts of a program if certain conditions are met (if condition is true) “.

Syntax:

If (Condition)

{  //Body of “ IF "

statement 1;

statement 2;

{

else

{ //Body of “ ELSE “

statement 1; 

statement 2;

}

Note: - If the statement block is only one statement, the braces are not necessary.

  

Example: - Scan a number from user and display message that number that enter is 

+ve or -ve.

#include <stdio.h>

#include<conio.h>

#include<iostream.h>

using namespace std;

Int main()

{

int n;

cout<“Enter a number<<endl;

cin>>n ;

if(n>=0)

cout<<"number is +ve" ;

else

cout<< “Number is –ve " ;

getch( );

return 1;

}

In above example user enter a number. This number is stored in N (variable) then condition is checked that number is greater then zero is less zero. If the number is grater then zero its means that condition is true then message appear that "Number is + ve " and if condition is false then message appear that "number is -ve".

NESTED IF

If an IF statement is tart in the body of other IF statement then this is called nested if statement.

it is used when we have multiple conditions to check and when any if condition contains another if statement then that is called ‘nested if’.

Syntax:

If (condition expression)

{

Block of statements

}

Else if (another condition expression)

{

Another block of statements

}

Else

{

Yet another block of statements}

In simple word when we have multiple choices or multiple conditions then we use nested if-structure. For this purpose we put an other if statement in the body of first if statement.

Example

Int main( )

{

int n ;

cout<<"Enter a number" <<endl ;

cim>>n ;

if(n== 1)

cout<<“You Enter One” ;

else

if(n==2)

cout<<You Enter Two” ;

else

if(n==3)

cout<<“You Enter Three” ;

else

cout<<“ You enter other the one , two or three " ;

}

getch( );

return 1;

}

in above example we see that if we enter 1(one) form keyboard then message appear that "You enter One" other wise condition is again tested end the result is prepared .

The switch Statement

This is another form of the multi way decision. It is well structured, but can only be used, in certain cases where;

Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (Int. long, short or char).

Each possible value of the variable can control a single branch.

A final, catch all, default branch may optionally be used to trap all unspecified cases.

Switch statement work similar as nested if statement works.

In this example user enter a character and this program decides whether you enter a, b, c or other then these character.

Int min( )

{

 char x ;

cout<< “Enter a character " ;

cin>>x;

switch (x)

{

case ' a ' :

cout<<" you enter A " ;

break ;

case ' b ' :

cout<< " you enter B " ;

break ;

case ' c ' :

cout<< " you enter C " ;

break;

default :

cout<< " You enter other then a , b , c" ;

}

getch( ) ;

}

Each interesting case is listed with a corresponding action. The break statement prevents any further statements from being executed by leaving the switch. Since case 3 and case 4 have no following break, they continue on allowing the same action for several values of number.

Loops

When we want to execute a statement or group of statement repeatedly then we use

Loops. In simple word when we do some work again and again for specified period of time in the same way then we use loops.

For example if we want to print message "hello C++" 100 times then there are two ways to perform this type of task.

First we use printf statement 100 time to print this message on the screen.

Second we write single statement in the body of the loop which print this message

100 time.

So we observed that second one method is simple and easy and less time consuming.

In C++ language we have choice of three types of loop, for , while and do while .

These loop are classified in two types

  • Count Control Loop
  • Event control Loop

Count Control Loop:

Each time the body of the loop is executed is called iteration. When the number of repetition (Iterations) is well known before the processing than we use count control loop. For example For Loop is an example of Count Control Loop.

Event control Loop:

When we not enough knowledge about the total iterations of the execution of loop then we use event control loop. Event control loop repeated until something happens with in the loop.

If you are making a angel food cake and the recipe reads “Beat the Mixture 300 strokes” its means you are executing count control loop. And if recipe reads “ Beat the Mixture until the Color of Mixture change in brown color “ its means you are executing event count loop.

I am sure you well understand these two structures. Now we discussed Three Loop

  • For loop
  • While Loop
  • Do While Loop

FOR LOOP

For loop is Count Control loop. The for loop works well, where the number of iterations of the loop is known before the loop is entered. The head of the loop consists of three parts separated by semicolons.

The initial value: - This is usually the initialization of the loop variable and its initial

Value this variable is called Loop Counter.

Condition: -The second part is a test; the loop is terminated when this returns false.

Step: - The third is a statement to be run every time the loop body is completed. This is usually an increment of the loop counter.

 

Syntax of for loop:

for (initial Counter ; test condition ; increment)

{

//Body of for Loop

statement 1;

statement 2;

statement 3;

}

Note: - If the statement block is only one statement, the braces are not necessary.

Example:

Following example give clear idea of using loop.

Int main( )

{

int i ;

for(i=1 ; I<=100 ; i++) ;

cout<< i ;

getch();

return 1;

}

This Program print 1 to 100 digit on screen so we see that only one statement executed and 1 to 100 number print on the screen because of header of this statement is for loop which repeatedly execute the statement below which print the number.

While Loop: -

The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed.

The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loops check the condition before the block is executed, the control structure is often also known as a pre-test loop.

Syntax:

While (condition)

{

statement 1 ;

statement 2 ;

statement 3 ;

}

Note: - If the statement block is only one statement, the braces are not necessary.

Example:

Following example give clear idea of using loop.

Int main()

{

int x = 1 ;

while (x < =100)

{

cout<<x;

x++;

}

getch( );

return 1;

}

This program also displays 1 to 100 digits on screen. But there is no counter as in for loop. In this while loop x++ increment in the value of x one time and transfer the control to while loop and check if x<=100 then again execute the printf statement and then increase the x. this loop is terminated when x increases the value of 100.

Do While Loop:

The do while construct consists of a block of code and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop. Contrast with the while loop, which tests the condition before the code within the block is executed.

The do while loops is similar to while loop, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once.

Syntax: -

Do

{

statement 1 ;

statement 2 ;

statement 3 ;

}

Note: - If the statement block is only one statement, the braces are not necessary.

Example: -

Following example give clear idea of using loop.

Int main()

{

int x = 11 ;

do

{

cout<< x;

} while (x <= 10) ;

getch( );

return 1;

}

We see as the value of x is greater than 10 in the start but printf statement executed one time and then condition is test which identify that x > 10 so return False and loop execution is terminated and control is transfer to next statement.

Continue Statement:

In some programming situation we want to take the control to the beginning of the loop by passing the statement inside the loop. Which have not yet been executed. For this purpose we use continue statement. When keyword continue is occurred then control transfer to the beginning of the loop without executing the statements after the continue keyword in the body of the loop.

For example if we want to print all the number from 1 to 100 but those number are not printed which are divisible by two. The C++ program for this purpose is as follow.

Int main()

{

int n ;

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

{

if(n%2==0)

continue ;

cout<< n ;

}

getch( ) ;

return 1;

}

Break Statement:

When we want to jump out form the loop without waiting to get back to test condition then we use Break statement.

Following program is best example to understand the break statement.

Int main ( )

{

int i ;

clrscr( );

for (I =0 ; I<=100 ; I++)

{

if (i==50 )

break ;

cout<< I ;

}

getch() ;

return 1;

}

We see that in this program we use for loop to display the number 1 to 100 . but using break statement before the cout statement stopped the loop when counter reached to 50 and loop is terminated.

Nested Loop:

The placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop. While all types of loops may be nested, the most commonly nested loops are for loops.

For example:

Int main ( )

{

int i , j ;

clrscr( ) ;

for(i=1 ; i<=3 ; i++)

for(j=1 ; j<=3 ; j++)

cout<< “Hello c++ “<<endl;

getch( ) ;

return 1;

}

In this above program inner loop is executed 3 times for every iteration of outer loop so total iteration are 9. Its means that printf statement repeated 9 time and “ Hello C++” is printed on the screen 9 times.

Array

Array is collection of variable, which are same in nature and store in contagious memory location. In simple word we say that array is collection of similar data element, which are, store in continues memory location with a single name.

We take an example to understand array. If we want to store the marks of 100 student in memory then we have two way.

  • First we declare 100 variables and store the marks.
  • Second is we declare a single subscripted variable which store the marks of 100

Student.

Of course second one is best way for-storing these types of values.

Subscripted variable:

it is the variable, which represent the individual element of array. It is use to access and manipulate the data element of array.

Individual array elements are identified by an integer index (subscripted value). In C

the index begins at zero and is always written inside square brackets.

There are two-type array used in C-Language

  • One Dimensional Array
  • Two Dimensional Array

0ne Dimensional Array (Linear array)

A linear array is also called one-dimensional array. The entire element stored in shape of vector means in one row or one column. The elements of the array stored respectively in successive memory locations. In linear array each element of an array is referred by one subscript.

Declaration of Array

Array is declared as we declare simple variable in the beginning with declaration statement.

Syntax: Data type array name [size of array] [=values]

Data type is any valid C data types like integer, character etc.

Array name is any valid variable name.

Size is total length of array.

Values are optional we specify the value of each element of array at time of

declaration of array.

For example

int num[3]={2,5,7];

2 , 5 and 7 are given 3 subscripted variable such that

num[0]=2

num[1]=5

num[2]=7

Example of array

Int main()

{

int st[5] ;

cout<< “ Enter the marks of 5 student “<<endl ;

for(i=0 ; i<=4 ; i++)

cin>> st[ i ] ;

clrscr( ) ;

cout<< “ Your entered List is " ;

for (i=0; i<=4 ; i++)

cout<<st[ i ] << endl;

getch ( ) ;

}

Above program gets the marks of five students and then after getting marks clear the

screen and then print list of all the marks that you entered.

String Processing

Character Array (String )

When characters store in array (in Consecutive memory location) then it is called string.

A string is a sequence of characters. Any sequence or set of characters defined within double quotation symbols is a string constant. In “ c++ “ it is required to do some meaningful operations on strings they are:

  • Reading string displaying strings
  • Combining or concatenating strings
  • Copying one string to another.
  • Comparing string & checking whether they are equal
  • Extraction of a portion of a string

The last character of the character array is NULL character. when we enter a string then each and every character take place in the array and when we press enter key then a NULL character will place in the end of the string which tell that this is end of the array.

For example:

Char name[ ]={ “T “, "O", "Q" , "E", "E", "R", "\0"}

Where "\0" is NULL Character.

Null Character play important role in string because this is only way which tell that where the string is end.

Then the string name is initializing to “ Toqeer “. This is perfectly valid but C offers a special way to initialize strings.

The above string can be initialized char name[ ]=”Toqeer”; The characters of the string are enclosed within a part of double quotes. The compiler takes care of storing the ASCII codes of characters of the string in the memory and also stores the null terminator in the end.

On the other hand when we print the string value then we use %s format specifier and there is no need for specify the index value of array.

Printf( "%s " , name)

You can also use

cout<<name;

Example:

#include <stdio.h>

#include<conio.h>

#include<iostream>

using namespace std;

int main()

{

char x[5];

cin>>x;

cout<<x;

return 1;

}

String class in C++

C++ has in its definition a way to represent sequence of characters as an object of class. This class is called std:: string. String class stores the characters as a sequence of bytes with a functionality of allowing access to single byte character.

std:: string vs Character Array

A character array is simply an array of characters can terminated by a null character. A string is a class which defines objects that be represented as stream of characters.

Size of the character array has to allocated statically. In case of strings, memory is allocated dynamically.

Character array do not offer much inbuilt functions to manipulate strings. String class defines a number of functionalities which allow manifold operations on strings.

#include <stdio.h>

#include<conio.h>

#include<iostream>

using namespace std;

int main()

{

 string x;

getline(cin,x);

cout<<x;

return 1;

}

 

What is Function in C Language?

A function in C language is a block of code that performs a specific task. It has a name and it is re-usable i.e. it can be executed from as many different parts in a C Program as required. It also optionally returns a value to the calling program.

In simple word we suppose you have a task, which is always performed exactly in the same way. Like monthly service of the motorbike. When you want it to be done, you go to the service station and say "its time of service do it now". You don't need to give instructions, because mechanic knows his job.

In the same way when we have some kind of work, which performs always in same way like that factorial of the number then we only, tell the number a function return the factorial.

Function in a C program has some properties discussed below.

  • Every function has a unique name. This name is used to call function from “main()” function or for any where. A function can be called from within another function.
  • A function is independent and it can perform its task without intervention from or interfering with other parts of the program.
  • A function performs a specific task.
  • A function returns a value to the calling program.

The C function has three different parts.

  1. Function declaration
  2. Calling function
  3. Function Definition

1) Function declaration: -

Function declaration is also called prototype. This is one line statement and always written before the declaration of main( ) function. Its consist on name, type of the function and arguments.

  • Where type represent the data type returned by the function.
  • Name is any valid names that represent the function.
  • Specify the type parameters, which are provided to function. If more then one parameters are used then commas separate them.

For example:

 Void display ( void ) ;

Where void means this function does not return any value and no values is passed to this function.

Int sum (int x, int y);

Hare int means that this function returns integer value. And two integer values passed to this function.

 

2) Calling Function: -

We can call function any where form any function. For this purpose we use calling statement.

Syntax:

Variable name = function name ( argument ) ;

Where variable name is optional if function return any value then we give variable name that store the returning value.

Arguments are those variables, which represent the values, which passing to function.

 3) Function Definition: -

Function Definition is actually the function, a task that is performed when we call this function. Function definition is self-alone single program always written as we write main ( ) function. Function Definition is written any where after the main function.

For example:

In following program we pass a number to function that calculate the factorial and print the answer.

void factorial( ); //Function Prototype

int main ( )

{

int x= 4;

factorial ( x ) ; // This is calling function

getch( ) ;

return 1;

}

void factorial (int a) // This is a Function definition

{

int f=1;

while(a!=0)

{

f= f * a ;

a--;

}

Cout<<f;

}

 

Returning the value form function:

When any function returns some value then we use RETURN keyword with some arguments.

Syntax :

Return ( x ) ; // X is the value, which is return to calling function

 

Advantages of using functions:

There are many advantages in using functions in a program they are:

  • The length of the source program can be reduced by using functions at appropriate places.
  • A function may be used later by many other programs this means that a c programmer can use function written by others, instead of starting over from scratch.
  • A function can be used to keep away from rewriting the same block of codes which we are going use two or more locations in a program.
  • Debugging is easier.
  • It is easier to understand the logic involved in the program.
  • Testing is easier.
  • Recursive call is possible.
  • Irrelevant details in the user point of view are hidden in functions.
  • Functions are helpful in generalizing the program.

Recursion:

When a function call its self in its body then this process is called recursion and this function is called Recursive function, sometime it is also called Circular definition.

èFollowing program give description about recursive function. N this program we calculate the factorial with the help of recursive function.

Int main ( )

int n , f ;

cout<< "Enter the number "<<endl ;

cin>> n;

f = fact ( n ) ;

cout<<" result is = "<< f ) ;

getch ( ) ;

return 1;

}

fact ( int x )

{

int r ;

if ( x = = 1)

return (1 ) ;

else

r = x * fact ( x - 1) ;

return ( r ) ;

 }

Passing Argument to function

There are two type of passing argument to function:

Pass By Value:

We take an example to understand this mechanism.

Int main ( )

{

int b = 10;

square (b);

}

void check (int n)

{

//body of function

Cout<< “ %d”<< n * n ;

}

In this function, ‘n’ is a parameter and ‘b’ (which is the value to be passed) is the argument. In this case the value of ‘b’ (the argument) is copied in ‘n’ (the parameter). Hence the parameter is actually a copy of the argument. The function will operate only on the copy and not on the original argument. This method is known as PASS BY VALUE.

Call by Reference:

When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call.

Int main ( )

{

int n = 10;

square (&n);

getch();

return 1;

}

void square (int *x)

{

Cout<< (*x) * (*x);

}

As you can see the result will be that the value of a is 100. The idea is simple: the argument passed is the address of the variable n. The parameter of ‘square’ function is a pointer pointing to type integer. The address of n is assigned to this pointer. You can analyze it as follows: &n is passed to int *x, therefore it is the same as:

Int * x = &n ;

This means that ‘x’ is a pointer to an integer and has the address of the variable n.

Within the function we have:

*x = (*x) * (*x) ;

* (star symbol ) when used before a pointer will give the value stored at that particular address.

 

Function Overloading

Defining more than one function with the same function-name such that they perform the same general task but a slight difference exists in their basic task is called function overloading. So, function overloading allows the same function to perform in different ways.

When more than one function are defined with the same name but different arguments, then this phenomenon is called function overloading. So, function overloading allows multiple function definitions with the same function name.

The functions in this case are called overloaded functions. The overloaded functions must be different in arguments i.e. their must be difference in the number or order or type of arguments of the overloaded functions. The return type of overloaded functions is not significant i.e. it may be same or may be different. It is bad programming practice to create overloaded functions that perform totally different tasks. Function overloading is a distinct feature of C++ as it is not available in C language.

Example of function overloading:

#include <stdio.h>

#include<conio.h>

#include<iostream>

using namespace std;

void sum(int x, int y);

void sum(float p, float q);

// Function prototype for the 1st 'sum function

int main()

{

 int x1, x2, s1;

 float f1, f2, s2;

cout << "Enter two integer numbers please: ";

cin >> x1 >> x2;

cout << "Enter two float numbers please:";

 cin >> f1 >> f2;

sum( x1, x2); // calls the first 'sum' function. sum( x1, x2);

sum( f1, f2); // calls the 2nd 'sum' function. sum( f1, f2);

getch();

return 1;

}

void sum(int x, int y)

{

//defining the 1st 'sum' function

// Here two integer numbers are added.

 int result1;

result1 = x+y;

 cout << "The summation of two integers is: "<< result1<< endl;

}

//End of the 1st 'sum function

 //defining the 2nd function

void sum(float p,float q)

{

float result2;

result2=p+q;

cout<<"The sum of the two float number is="<<result2;

} //end of the 2nd finction

POINTERS

Pointer is a way of accessing a value, which is stored in memory with out referring to the variable name directly. Pointer refers the address of the variable.

Pointer variable:

In c a pointer variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.

 For example:

int *K ;

Where K is pointer variable, which store the address of any other variable. When we declare variable then three type of information about that variable take place.

  • Reserve space in memory to hold the integer.
  • Associate a name with this memory.
  • Store the value at this location.

For example:

 int n = 1 0 ;  //  Variable Name

Pointer declaration:

A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable.

type * variable name

Example:

int * ptr ;

float *string ;

What is Reference operator (&)

Reference operator is used to get the address of a variable. It is represented by symbol '&'. It is also called 'address operator.

Example: Use of reference operator, read the following program.

#include <conio.h>

 #include <iostream.h>

Int void main()

int k; k= 5;

cout << "The value of variable k is: "<<k<< endl;

 cout << "The address of k is: " <<&k;

getch();

return 1;

}

OUTPUT The value of variable kis: 5 The address of k is: 0x8fb31714

What is class?

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 main purpose of C++ programming is to add object orientation to the C programming language and classes are the central feature of C++ that supports object-oriented programming and are often called user-defined types.

A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows −

Example:

class book {

public:

string bookname; // name of the book

int pages; // pages of the book

int price; // price of the book

};

Define C++ Objects

A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box −

Example:

book book_info; // Declare book_info of type book class

Programming Example of Class and Object:


#include <stdio.h>
#include<iostream>
using namespace std;
class book
 {
	public:
	string bookname; // name of the book
	int pages; // pages of the book
	int price; // price of the book
};

int main()
{
book book_info; // Declare book_infor of type book
// book specification
cout<<"enter the book name"<<endl;
getline(cin,book_info.bookname);
cout<<endl;
cout<<"enter the book Pages"<<endl;
cin>>book_info.pages;
cout<<endl;
cout<<"enter the book Price"<<endl;
cin>>book_info.price;
cout<<endl;

cout << "Your book Information : " <<endl;
cout << "Name of The Book:"<<book_info.bookname<<endl;
cout << "Price of The Book:"<<book_info.price<<endl;
cout << "Totoal Pages of The Book:"<<book_info.pages<<endl;
return 0;
}


Constructor:

Constructor is a special member function which is executed when an object is created.

When an object is created, space is required in memory to hold it. This is the responsibility of constructor to allocate space in memory for an object and may also initialize it

When an object is created, C++ calls the constructor for that object. If no constructor is defined explicitly/manually in the program, then C++ creates and invokes a constructor callout default constructor which allocates memory space for object. The general syntax to define a constructor is as under.

Constructor-name( arguments)

// body of constructor

Constructor-name' is the name of constructor. It must me as the name of the class where it is defined. The arguments are optional. The body of constructor can contain any number of statements.

Example, suppose we have defined a class named complexno.

Now a constructor having no arguments can be defined as under

complexno()

// body of the constructor 'complexno'

 

A Programming Example of constructer


#include<stdio.h>
#include<iostream>
using namespace std;
class complexno
{
	private:
	float x,y;
	public:
	complexno( ) // defines a constructor named 'complexno
	{
	cout << "Enter the real part of complex number:
	cin >>x;
	cout << "Enter the imaginary part of complex number:
	cin>>y;
	}

	void show()
	{
	cout << "The complex number is:"<<x<< " + y" <<y;
	}

};

 // End of the class 'complexno'

Int main()
complexno c1; // declares c1 as of the class 'complexno'
c1.show(); //calls the 'show' function of object c1
return 1;
}

Constructor Overloading

Constructor Overloading Defining more than one constructor with the same name but with different number, type or order of arguments is called constructor overloading.

Like other functions, it is easy to overload constructors.

Example: The following program will explain the concept of constructor overloading. The program inputs two complex numbers and then displays them.


#include<stdio.h>
#include<iostream>
using namespace std;
class complexno
{
	private
	float a, b;
public:
	copmplexno () // defines the first constructor
	a = 2.5 ;
	b= 7.9;
	}
	// End of the first constructor
	complexno( float x,float y)
	// defines the second constructor
	x=a;
	y=b;
	} //End of the second constructor void show()

	Void show()
	{
	cout<<a<< " + " << b ;
	} //End of the class 'complexno'
};

int main()
complexno c1; //declares c1 as an object of class 'complexno
complexno c2 (5.3,6.4); // declares c2 as an object of class
cout << "The first complex number is: "; c1.show();
cout << endl << "The second complex number is: ": c2.show();
retuen 1;
}

Destructor

 Destructor is a special member function, which is executed automatically when an object is destroyed. We know that whenever an object is created, constructor is executed to allocate memory space for the object. But, whenever an object is destroyed what happens to its allocated memory space? Its answer is quite simple i.e. its memory space is de-allocated or released. So, to de-allocate/release memory space when an object is destroyed, C++ implements the concept of destructor. Thus the task of destructor is to de-allocate memory space when an object is destroyed.

The general syntax to define a destructor is as under.

~Destructor-name()

// body of destructor "cl' to objec statement is

Here 'Destructor-name' is the name of destructor. It must be same as the name of class where it is defined. The body of destructor can contain one or more statements.

Example, suppose we have defined a class named complexno'. Now a destructor inside this class can be

~ complexno()

// body of destructor

Operator Overloading

Operator overloading is the process of redefining the existing C++ operators in such a way to operate on data types over which these operators can't perform operation ordinarily.

OR Operator overloading is the phenomenon in which we give the capability to existing C++ operators to operate on data type over which they cannot operate ordinarily. So, operator overloading enables the existing operators to perform in different ways.

Suppose we want to add two integer values. We may write the following segment of code.

a = 45;

 b = 20;

 c= a + b;

The above addition operation is correct/valid because the operator (+) can operate on integer data (which is a built-in

data type).

On the other hand, if we write the following segment of code to add two character values,

char ch1,ch2,ch3;

ch1=’a’;

ch2=’b’;

ch3= ch1 + ch2;

So, what will be the solution to such situations? The easy and simple solution to handle such situations is operator overloading in which this type of operations are made valid. The operators that can be overloaded include:

How to Overload an Operator?

The general syntax of the function that overloads an operator is as under.

Return-type operator Operator-symbol (arguments list)

{

// body of overloading function

}

Return-type may be any data type including a user data type, operator is a key word, and Operator

is the symbol of operator which is to be overloaded. Argument list' is optional.

The body of the function is the code to overload an operator.

Example:

void operator ++ ()

In this case 'void' is the return-type of the function, 'operator Is a keyword followed by the operator-symbol (++) which is to be overloaded, followed by parentheses with no argument.

Programming example of Operator overloading:


#include <stdio.h>
#include<conio.h>
#include <string.h>
#include<iostream>
using namespace std;
// Class to implement operator overloading
// function for concatenating the strings
class AddString
 {
	public:
	string s1;
	string s2;
	// Parametrized Constructor
	AddString(string str1, string str2)
	{
	s1=str1;
	s2=str2;
	}

	// Overload Operator+ to concat the string
	string operator+()
	{
	return(s1.append(s2));
	}
};
int main()
{
// Declaring two strings
string a1 = "hello";
string a2= "C++";
// Declaring and initializing the class
// with above two strings
AddString op(a1, a2);
// Call operator function
cout<<+op;
return 0;
}

Inheritance

Inheritance is the process in which new classes can be created /derived from existing classes. The newly created class is called child class or derived class or sub-class, whereas the existing class is called parent class or base class or super class. The child class contains/inherits all the features or characteristics of its parent class. However, we can add additional features to the child class also. Note that the features of a class are represented in the form of data member and member functions inside the class. Once we have defined a class, then we can derive as many classes as we need from it easily. The common life example of parent class may be 'Fruits' and that of its child classes may be 'Apple' and 'Mango'. Similarly, 'Computers' is a parent class and its two child classes are 'Laptop' and 'Desktop'. Here, the parent class 'Computers' may have properties/features such as execution speed', 'HDD', 'price' etc. Its child classes now can have all the features of the parent class, and may have its additional features also. For example, a laptop may have additional features such as Bluetooth and web camera which is specific to laptop Inheritance is an important feature of OOP. The main purpose of inheritance is code reusability, and to save programmer time.

1- Single-inheritance

  1. Multiple-inheritance
  2. Single-Inheritance:

When a child class or classes is/are derived from a single parent class then such inheritance is called Single- inheritance. Suppose we have a parent class 'A' and its child classes are

B', 'C'. The parent class 'A' has the features al, a2 and a3. Now the child classes 'B' and 'C' will have all these features. The child class 'B' may have additional features such as b1 and b2. Similarly, the child class 'C' may have additional features such as c1 and c2. The additional features b1, 62 and cl, c2 differentiate child class 'B' from 'C'. They also differentiate the child classes from their parent class.

The common life example of single-inheritance is that of "Mammals', 'Man' and 'Deer' in which the two child classes (i.e. Man and Deer) are derived from a single parent class Mammals.

  1. Multiple-Inheritance:

 When a child class or classes are derived from more than one parent classes then such inheritance is called Multiple-inheritance. Suppose we have a child class 'C' which is derived from two parent classes 'A' and 'B'. The parent class 'A' has features a1, a2 and a3 whereas the parent class 'B' has features b1, b2 and b2. Therefore, the child class 'C' will have features a1,a 2, a3, b1, b2. The class "C' may also have additional features such as c1 and c2.

The common life example of multiple-inheritance is that of Horse'. Donkey' and Mule' in which the child class 'Mule' is derived from two parent classes i.e. 'Horse' and 'Donkey'.

Syntax:

Class B: Access specifier A

{

//body of child class B

};

Programming Example:


#include <stdio.h>
#include<conio.h>
#include <string.h>
#include<iostream>
using namespace std;
//class general
{
	public:
	string subject1;
	string subject2;
	void display()
	{
	cout << "Subject 1: English" << endl;
	cout << "Subject 2: Urdu" << endl;
	}
};

// group 1 class
class group1 :	public general
{
public:
	void display2()
	{
	cout << "Subject 3: Math" << endl;
	cout << "Subject 4: Physics" << endl;
	}
};
// class group 2.
class group2 : public general
{
	public:
	void display3()
	{
	cout << "Subject 3: Math" << endl;
	cout << "Subject 4: Computer" << endl;
	}
};

int main()
{
int choice;
general sub;
group1 sub2;
group2 sub3;
cout<<"Select any Group"<<cout<<endl;
cout<<"1:MS-Math"<<endl;
cout<<"2:MS-computer"<<endl;
cin>>choice;
cout<<endl;
cout<<"Yours Subject are:"<<endl;
if(choice==1)
{
sub2.display();
sub2.display2();
}
else
{
sub3.display();
sub3.display3();
}
return 0;
}

Function Templates

A function template can work with different data types at once but, a single normal function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data, you use function overloading to create two functions with the required function declaration.

One of the better approach would be to use function templates because you can perform the same task writing less and maintainable code.

Syntax:

Function template starts with the keyword template followed by template parameter/s inside < > which is followed by function declaration.

template <class T>

T someFunction(T arg)

{

... .. ...

}

Where , T is a template argument that accepts different data types (int, float etc), and class is a keyword.

You can also use keyword typename instead of class. Like template <typename T>

Programming Example of Function Templates:


#include <stdio.h>
#include<conio.h>
#include <string.h>
#include<iostream>
using namespace std;
// template function
template <typename check> // you can also write template <class check>
check Large(check n1, check n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout << "Enter two integers:\n";
cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value.";
return 0;
}




View and Download More Tutorials !

C ++ Class Notes