Static Member Function and Variables

In a C++ programming we can create static function and variable by using the “static” keyword.

Static Variables

 In C++ programming we can create a static variable by placing the “static” keyword before the variable declaration.

Once a variables declared as static, only one copy of that variable is created for the whole class.

 When a variable is declared as static, by default it is initialize to zero.

Output

Note: In the above figure we have a two object (object 1 & object 2) we object occupies a separate memory for variable(for ex: for variable 1 , object1 and object2 both will occupy the memory) . But when a variable declared as a static then only one memory location is occupy for all object.

Static function

In C++ programming we can create a static function by placing the “static” keyword before the function declaration .

A static function can only assess static member variable and member function. 

In a C++ it is also possible to call a  static member function without object.

Static public member function:

Example: WAP to declare public member function and call them from main().

Output

Size of the Object in C++

In a C++ programming language,  size of any object is equal to the sum of size of all the data members of the class.

In a below program,  class contain three data type and three variable. 

Data type int occupies 4 bytes, float occupies 4 bytes, and char occupies 1 byte. their sum is  9 bytes .

In this program size of individual of object is 9 byte. We can know the size of object/class by using  sizeof() operator.

Output

Inline Function in C++

In a C++ language  An inline function is similar to macros. Inline function is also called as open subroutine because their code is replaced at the place of function call in the caller function. 

In a C++programming  normal  function  are known as closed  subroutine because when such function are called ,the control passed to the function.       

inline function  reduces  the overhead of accessing the member function, increases the efficiency of program and allows quick execution of function.

Example of inline function

Output

Note:
1 Inline function used when the member function contains few statement.
2  If function takes more time to execute , then it must be declared inline.                     .

   

Member function in C++

In a C++,  we can use the function within the classes. These functions are called as a member function. It can be public ,private & protected.

Public member function: in a below program we have created a public function which can be accessed from outside of class.

Output

Private member function:  in a below program we have created a private function which can’t be accessed from outside of class.

Output

Description: when we compile this program we will get an error message. Because show() function cant be access from main() because it is a private member function.

How to access private member function

 We can access private member function from public member function. In the below program we have created one public function display() and one private function show() and we can call the show() from within the display().

Output

Define a member function outside of the class

In a C++ language we can define a function inside  as well as outside of the class. To define a function a function outside of the class syntax is:

Syntax:

Datatype class_name :: function name

Output

In the above program we have declare two function inside class and define outside of the class.

a private member function outside of the class

In a below program we have define a private function display() outside of the class which can’t be accessed from outside of class. If we try to access then we will get an error message.

Output

Solution of above program: We can access private member function from public member function. In the below program we have created one public function show() and one private function display() and we can call the display() from within the show().

OUTPUT

Access Private Data Member/Variable

In a C++ we can access private data member within the class. It can’t be used outside of the class.

Output

Note: we can’t access private data member outside of the class. The private data can be accessed by only member function and friend  function of that class. 

Solution of above program: The private data can be accessed by only member function and friend  function of that class. 

Output

Example. Write a C++ program to create a class and member function & find the factorial of the number given by user.

Output

Access Specifiers

In a C++ language there are three types of access specifiers . They are: public private and protected.

Public: A public data can be accessed by out side of the code in which it is defined .

Private : A private data can not be accessed by outside of the code in which it is defined. The private data can be accessed by only member function and friend function of that class.

Protected : A protected access specifier is similar to the private only difference is that it has a access to their derived classes.

Default : By default access specifier is private means when we have not specified access specifier it will be private.

Syntax for declaring a class:

Example

In the above example we have created a new class “student”. Inside the student class we have created two private data member age & name[20] and two public member function input() & show().

Example :  write a program to add two number by using class and public data member.

Output:

Note: In the above program we have created a class “example” which hold public integer data x,y and inside the main function we create a object of class example name obj. By using the object and (.) dot operator you can access public data member of the calss.

Note: we can create more than one object of the class. For example:

More than one object of the class:

in a C++ we can create one or more than one object of the class. In the below example we have created two object of class “example”.

Output

Class & Object in C++

Class:  A class is a user defined data type which contains the data members and member function. A class forms the basis for object oriented programming.

 It describes the shape and nature of the object .Any concept that we want to implement in oop’s must be encapsulated in class.

The internal data of the class are called data members and functions are called member functions.

The variable of the class are called object or instance of the class.A class is a template for an object and an object is an instance for a class.

Syntax for declaring a class:

Example

In the above example we have created a new class “student”. Inside the student class we have created two private data member age & name[20] and two public member function input() & show().

Object: we can access data members and member function outside of the class by using the object. Object is a run time entity. 

Syntax for object creation:

Class_name   object_name;

Example:    student   obj;    

Note:    Here student is a name of the class and “obj” is a name of the object.

Note: we can create more than one object of the class. Foe example:

Note: By using the object and (.) dot operator  you can access public data member of the calss.

Pointers in C++

In  a  C++ programming language, variable is used to hole the value & this variable stored in a memory.  Each variable has a address to identify where these variables actually stored in a memory.  

 In a C++  programming language, pointer is a variable which can hold the address of another variable.  

 Accessing Address of Variable

In a system every memory location has its address & we can access the address using ampersand (&) operator. This ampersand (&) operator  denotes an address in memory. 

Ex:   int  i = 20;
      char c = ‘a’;

In the above example, there are two variable i & c. Integer variable “i” stores the value 10 at memory location 1024(for example) and character variable “c” stores the value ‘a’ at memory location 1026.

cout<<“\n value of  variable i=  “<<  i ;
cout<<“\n value of  variable c=  “<< c ;

Output

value of  variable i= 20
value of  variable c= a

If we want to print the address of variable ‘i and c’ then we need ampersand (&) operator  .

   cout<<“\n Address of  variable i =  “<< &i ;
   cout<<“\n Address of  variable c= “<< &c ;

Output:           Address of  variable i =   1024
                        Address of  variable c=   1026

Note: When you run this program, address are printed might be different.Example: Write a program to print the address of the variable.

#include using namespace std;

Output

Note: Each and every time when you run this program these variables stored in a different memory location.

Pointer Variable

pointer  variable is hold the address of another variable.

Output

Value at address

In the above example, there are two variable, first is normal variable ‘i’ & pointer variable ‘ptr’. Integer variable “i” stores the value 10 at memory location 1024(for example) and pointer variable “ptr” stores the address of variable  ‘i’ at memory location 3045.

Example:

#include

Output:

value of  variable i=  10

Note: Pointer variable “ptr” prints the address of variable and “*ptr” prints the value of i. *variable name (*ptr) is also called value at address.

Example:

Output

Note: When you run this program, address are printed might be different.

Pointer to Pointer

In a C language, a pointer is an address. Normally, a pointer variable contains the address of a another variable. 

A pointer to a pointer is a chain of pointers. 

Or

Pointer to pointer means one pointer variable holds the address of another pointer variable.

Example:

Output

NULL Pointers

A pointer that is assigned NULL is called a null pointer. We must initialize NULL pointer during variable declaration.

A null pointer refers to pointer variable that does not point to a valid address.

Generally NULL pointer is used when you do not have an exact address to be assigned.

Output

Arrays in C++

Arrays is a kind of data structure that can store a elements of the same type. Arrays stores the elements in a contiguous memory locations.

Array is a collection of variables of the same type.

 For example: we want to declare 100 integer variable

Instead of declaring 100 individual variables, such as

int number0, number1,number2,number3, … …., number99;

you declare one integer array variable such as

int number[100];

here number[100] is an integer array of size 100, means this array can store 100 integer value.

Array indexing starts from index 0 to n-1. Means first integer number store in array number[0], second integer number store in array number[1], third integer number store in array number[2], and so on. Here 100th  number store in array numbers[99].

Array In C++

Declaring Arrays

Syntax of declare an array in C:

Data_type  arrayName [ arraySize ];

This is called a single-dimensional array.

The arraySize must be an integer constant greater than zero.

datatype can be any valid C data type.

Example: write a program to create integer array and store 5 integer number and print.  

Output

Element Position in Array

Description : In the above program,   “int  num[5]” array can store 5 element in a contiguous memory locations from index 0 to 4.         

Example: Write a program to take 5 number from user and store integer number in integer array and print.  

Output

Another way to Initialize Array

 We can also initialize array by this way:

int num[5] = { 54 , 4,  13,  2,  17 };

above integer array num[5], stores five numbers. Where num[0] store 54, num[1] store 4….. , & num[4] store 17.

Output

Multi-dimensional Arrays 

C++  programming language also support multidimensional arrays.

Syntax of multidimensional array declaration:

Data_type    array_name[size1][size2]…[sizeN];

For example, if we want to creates a three dimensional integer array −

int  num[5][10][4];

Two-dimensional Arrays

The simplest form of multidimensional array is the two-dimensional array. if we want to declare a two dimensional integer array of size [x][y] ( where x is a  number of rows and y is a number of columns ) you would write something as follows −

 int  a[3][4];

In the above line we have created two-dimensional integer array ”a” with 3 rows and 4 columns.

Two Dimensional Array

Initializing Two-Dimensional Arrays

In a C++ programming language  Multidimensional arrays may be initialized by specifying bracketed values for each row. For example we want to create an integer array with 3 rows and each row has 4 columns.

Above the nested braces indicates the intended rows.

The following initialization is equivalent to the previous example −

int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

which indicate the nested braces for intended row, are optional.

Accessing Elements of Two-Dimensional Array

Create a two-dimensional array of size 3*3 and  nested loop is used to handle a two-dimensional array −

Output

Example: Write a program to create 3*3 matrix and take all elements of matrix as an input from user and print it.

Output

Addition of Two Matrix

Example: Write a program to add two matrix. Firstly, ask from user order of matrix( number of rows and column). Then take the elements of matrix from user as a input and print the resultant matrix

For example, if a user input order as 3,3, i.e., three rows and three columns and

First matrix                      

1          2          3
4          5          6
7          8          9

Second matrix:

9          8          7
6          5          4
3          2          1

then the output of the program (addition of the two matrices) is:

10        10        10
10        10        10
10        10        10

Matrix addition program in C++

Output

Matrix multiplication

Example: Write a program to multiply two matrix. Firstly, ask from user order of matrix( number of rows and column). Then take the elements of matrix from user as a input and print the resultant matrix.

Functions in C++

In a C++ programming language a function is a group of statements that together perform a special task. Every C++ program has at least one function, which is main().

In a C++ library has a numerous predefined or built-in functions. For example, strcat() to concatenate two strings, main() from where program execution starts. 

In a C++  programming function has a 3 part:

  • Function declaration
  • Function definition
  • Function call

Note: In a C++ program we can remove the function definition but we must place the function definition  before the main() function.

Function declaration : function declaration tells the compiler about a function’s name, return type, and parameters.

A syntax of function declaration –

Example of  the function declaration is as follows −

here int is a return type of function which tells function will return integer value and max is a name of the function. “ int num1, int num2” is a parameter list which tells max function will receive two integer arguments. Arguments are optional which depends on program requirements.

Function definition : function definition is an actual body of the function.

Syntax of function definition:

function definition consist a return type, function name, parameter list and body of the function.

Function call : whenever  program calls a function, the flow of control is transferred to the called function definition. A called function performs a defined task and when flow of control reached to function-ending closing brace, flow of control returns to back to the main program.

Example of a user defined function.

Output

Description: Program execution start from main() function. In main() when     DemoFunction();  executes it calls and transfer control to the function definition. Then statements of DemoFunction() execute and print “Hello Aditya”.

Note: In a C++ function can be called multiple times.

Output

Note: In a C++ program we can remove the function definition but we must place the function definition  before the main() function.

Output

User-defined function can’t declared after the main()

In a C++ program we can remove the function definition but we must place the function definition  before the main() function.  If we place the function definition after main() then we will get the error message. Because in a C++ execution occurs from top-to-bottom and if the function is not declared above main(), the program is unaware of it.

Categories of function

We can categories the function as:

  • Function with no argument, no return value
  • Function with  argument but  no return value
  • Function with  argument and  return value
  • Function with no argument, but  return value

Function  with  no  argument  & no return value

Example: Write a program to find the area of circle using function with no argument, no return value.

The formula for the area of the circle is :

Area_circle = Π * r * r

Program: To calculate Area of Circle

Output

Function  with  argument  but  no return value

Example: Write a program to find the area of circle using function with argument but no return value.

Output

Function  with  argument  &  return value

Example: Write a program to find the area of circle using function with argument but return value.

Output

Function with no argument but  return value

Example: Write a program to find the area of circle using function with no argument but return value.

Output

Call by value & Call by reference

Call by value : Whenever we call a function and passes the value of variable to the called function is called call by value.

Output

Call by reference : Whenever we call a function and passes the reference of variable to the called function is called call by reference. In the call by reference, to pass the reference of the variable we use pointer.

Output

Decision Making Statement

In the C++ language decision making statement executes if the given condition is  true otherwise conditional block will never execute.

C++ language assumes non-zero and non-null values as true, and zero or null is assumed as false value.

There are following types of decision making statements in C++ programming language.

if statement

Syntax of an ‘if’ statement −

if(Condition) {
/* statement will execute if the condition is true */
}

In a ‘if’ statement if the Condition is true, then the block of statement of the ‘if’ statement will be executed. If the Condition is false, then the block of statement of the ‘if’ statement will not executed and control sent to the next line of if block.

Example: Write a program to demonstrate the ‘if’ statement.

Output

In the above program if reverse the ‘if’ condition of ‘if’ statement then the condition will be false and ‘if’ block will never execute.

Output

if-else  statement

Syntax of an ‘if-else’ statement −

if(Condition) {
/* if-statement will execute if the Condition is true */
}
else
{ if the condition is false then else block will execute
}

In a ‘if-else’ statement if the Condition is true, then the block of statements of the ‘if’ statement will be executed. If the Condition is false, then the block of code of the ‘else’ statement will executed.

Example: Write a program to  take two numbers from user and find the grater between them using ‘if-else’ statement.

Output

Nested -if statement
In a C language we can use if statement inside another if statement(s).
Syntax of an ‘nested -if’ statement −


if(condition 1) {
/* statement will execute if the condition 1 is true */
If (condition 2) { /* statement will execute if the condition 2 is true */
}
}

Example: Write a program to take two numbers from user if both number are between 1 to 9 then print “Good” using nested-if statement.

Output

Nested if-else statements

In a C language we can use  if or if-else statement inside another if or  if-else statement(s).

Syntax of an ‘if-else’ statement −

if(condition 1) { /* statement will execute if the condition 1 is true */
If (condition 2) {
/*if- statement will execute if the condition 1 & 2 both are true */
}
else {
/* else-statement will execute if the condition1 is true Condition2 is false */
}
}
else {
If (condition 3) {
/* statement will execute if the condition 3 is true */
}
}

Example: Write a program to  take three numbers from user and find the grater among them using ‘nested if-else’ statement.

Output