1 of 53

Global Variables

2 of 53

Global Variable

  • Global variables are defined outside of all the functions, usually on top of the program.
  • The global variables will hold their value throughout the life-time of your program.
  • A global variable can be accessed by any function.
  • A program can have same name for local and global variables but value of local variable inside a function will take preference.

3 of 53

Global Variable

  • int m=10; // global variable
  • Void main()
  • {

int m=20; //local to main

  • {

int k=m;

int m=30;

cout<<k;

cout<<m;

cout<<::m;

  • }

cout<<m;

cout<<::m;

  • }

4 of 53

  • #include <iostream>
  • using namespace std;

  • int g = 20;

  • int main ()
  • {
  • int g = 10;
  • cout << g;
  • return 0;
  • }

5 of 53

  • #include <iostream>
  • using namespace std;
  • int g;
  • int main ()
  • {
  • int a, b;
  • a = 10;
  • b = 20;
  • g = a + b;
  • cout << g;
  • return 0;
  • }

6 of 53

Functions

  • A function is a group of statements that together perform a task.

  • Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.

  • A function declaration tells the compiler about a function's name, return type, and parameters.

  • A function definition provides the actual body of the function.

  • The C++ standard library provides numerous built-in functions that your program can call.
  • For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.

  • A function is known with various names like a method or a sub-routine or a procedure etc.

7 of 53

Defining a Function

  • The general form of a C++ function definition is as follows −

  • return_type function_name( parameter list )
  • {
  • body of the function
  • }

8 of 53

Example

  • #include <iostream>
  • using namespace std;
  • int max(int num1, int num2);
  • int main ()
  • {
  • int a = 100;
  • int b = 200;
  • int ret;
  • ret = max(a, b);
  • cout << "Max value is : " << ret << endl;
  • return 0;
  • }

  • int max(int num1, int num2)
  • {
  • int result;
  • if (num1 > num2)
  • result = num1;
  • else result = num2;
  • return result;
  • }

9 of 53

Function Prototyping

  • Helps the compiler by giving it to a prior information about a function.
  • The prototype describes the function interface to the compiler by giving details such as number and type of arguments and type of return values.
  • Function prototype is a declaration statement in calling program .

Type function_name(argu_list);

10 of 53

  • Argument List contains the types and names of arguments that must be passed to the function.

E.g. float volume(int x,float y,float z);

  • Each argument variable must be declared independently.

E.g. float volume(int x,float y,z); // illegal

11 of 53

  • In function declaration, Names of arguments are dummy variables and therefore they are optional.

So, float volume(int,float,float);

  • In function definition, names are required.

Float volume(int a,float b,float c)

{

Float v=a*b*c;

}

12 of 53

Prototyping Example

#include <iostream.h>

Float square(float);

Void main()

{

Float x,sqx;

Cout<<“enter no.”;

Cin>>x;

Sqx=square(x);

Cout<<sqx;

}

Float square(float a)

{

Float s;

S=a*a;

return(s);

}

13 of 53

Default Arguments

  • C++ allows to call a function without specifying all its arguments.
  • The function assigns a default value to the parameter which does not have a matching argument in the function call.
  • Default values are specified when the function is declared.
  • e.g.

float amount(float principal,int time,float rate=0.15);

14 of 53

  • Function call like

Value=amount(5000,7); // one missing argu

i.e.Default value of 0.15 for rate of interest.

  • Function call like

Value=amount(5000,5,0.12); passes an explicit value of 0.12 to rate.

  • Default arguments are useful in situations where some arguments always have the same value e.g. Bank interest.

15 of 53

  • Only the trailing arguments can have default values.
  • We must add default values from right to left.
  • We can not provide a default value to particular argument in the middle of an argument list.

int mul(int i,int j=5,int k=10);

int mul(int i=5,int j);

int mul(int i=0,int j,int k=10);

int mul(int i=2,int j=5,int k=10);

16 of 53

Function Overloading

  • Overloading refers to the use of the same thing for different purposes.

  • Function overloading means we can use the same function name to create functions that performs a variety of different tasks.

  • Also known as function polymorphism.

17 of 53

  • Function would perform different operations depending on the argument list in the function call.

  • The correct function to be invoked is determined by checking the number & type of the arguments but not on the function type.

  • Example

18 of 53

Add() function

//Function declaration

  • Int add(int a,int b);
  • Int add(int a,int b,int c);
  • Double add(double x,double y);
  • double add(int p,double q);

//Function Call

  • Cout<<add(5,10);
  • Cout<<add(15,10.0);
  • Cout <<add(12.5,7.5);
  • Cout<<add(5,10,15);

19 of 53

Default arguments & Function overloading Example

Void sum(int x=10,int y=20);

Void main()

{

Sum();

Sum(5);

Sum(5,15);

}

Void sum(int x,int y)

{

Int z=x+y;

Cout<<z;

}

20 of 53

C++ Class Definitions

  • 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 by a semicolon.
  • For example, we defined the Box data type using the keyword class as follows −
  • class Box
  • {
  • public:
  • double length; // Length of a box
  • double breadth; // Breadth of a box
  • double height; // Height of a box
  • };

21 of 53

Define C++ Objects�

  • 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

  • Both of the objects Box1 and Box2 will have their own copy of data members.

22 of 53

Accessing the Data Members�

  • #include <iostream> using namespace std; class Box
  • {
  • public:
  • double length; double breadth;
  • double height;
  • }; �int main()
  • {
  • Box Box1;
  • Box Box2;
  • double volume = 0.0;
  • Box1.height = 5.0;
  • Box1.length = 6.0;
  • Box1.breadth = 7.0;

  • Box2.height = 10.0;
  • Box2.length = 12.0;
  • Box2.breadth = 13.0;

  • volume =
  • Box1.height * Box1.length * Box1.breadth;

  • cout << "Volume of Box1 : " << volume <<endl;

  • volume = Box2.height * Box2.length * Box2.breadth;

  • cout << "Volume of Box2 : " << volume <<endl;
  • return 0;
  • }

23 of 53

  • The public data members of objects of a class can be accessed using the direct member access operator (.)

  • private and protected members can not be accessed directly using direct member access operator (.)

24 of 53

Class A

{

int somedata;

public:

void setdata(int d)

{

somedata=d;

}

void showdata()

{

cout<<somedata;

}

};

void main()

{

A s1,s2;

s1.setdata(10);

s2.setdata(20);

s1.showdata();

s2.showdata();

}

25 of 53

Static Data Members

  • Data members of class can be static.
  • Normally used to maintain values common to the entire class.

Characteristics:-

1. It is initialized to zero when the first object of class is created.

-No other initialization is permitted.

2.Only one copy of that member is created for the entire class and shared by all the objects of that class.

-No matter how many objects are created.

26 of 53

int item::count;�must be defined outside the class.�Initial value can also be assigned to the variable.�

Class item

{

Static int count;

Public:

getdata()

{

count ++;

}

getcount()

{

cout<<count;

}

};

Int main()

{

item a,b,c;

a.getcount();

b. getcount();

c.getcount();

a.getdata();

b.getdata();

c.getdata();

a.getcount()

b.getcount();

c.getcount();

}

27 of 53

  • Type and scope of each static member variable must be defined outside the class definition.

  • This is necessary because the static data members are stored separately rather than as a part of an object.

  • Since they are associated with the class itself rather than with any class object. So, called as class variables.

28 of 53

Class A

{

Public:

Static int value;

};

int a::value=1;

int main()

{

A s1;

s1.value=2;

A s2;

cout<<s2.value;

return 0;

}

29 of 53

Static Member Functions

  • Like static variables, we have static member functions.

Properties:-

  1. A static function can have access to only static members(function or variable) declared in the same class.

2. A static member function can be called using the class name(instead of its objects).

30 of 53

#include <iostream>

using namespace std;

class test

{

static int count;

int code;

public:

void setcode()

{ code=++count;

}

void showcode()

{

cout<<code;

}

static void showcount(void)

{

cout<<count;

}

};

int test::count;

int main()

{

test t1,t2;

t1.setcode();

t2.setcode();

test::showcount();

test t3;

t3.setcode();

test::showcount();

t1.showcode();

t2.showcode();

t3.showcode();

return 0;

}

31 of 53

CONSTRUCTORS�

32 of 53

Constructors�

  • A constructor in C++ is a special method that is automatically called when an object of a class is created.

  • special member function called the constructor which enables an object to initialize itself at the time of its creation. This is known as automatic initialization of objects.

  • To create a constructor, use the same name as the class, followed by parentheses ()

33 of 53

Example�

class MyClass

{      // The class�  public:            // Access specifier�    MyClass()

{      // Constructor�      cout << "Hello World!";�    }�};��int main()

{�  MyClass myObj;    

// Create an object of MyClass (this will call the constructor)� 

 return 0;

}

34 of 53

Special characteristics of Constructors

  • They should be declared in the public section
  • They do not have any return type, not even void
  • They get automatically invoked when the objects are created
  • Like other functions, they can have default arguments
  • Constructors cannot be virtual.

35 of 53

Types of Constructors

C++ offers four types of constructors.

These are:

  • Do nothing constructor
  • Default constructor
  • Parameterized constructor
  • Copy constructor

36 of 53

Do nothing constructors

  • Do nothing constructors are that type of constructor which does not contain any statements. Do nothing constructor is the one which has no argument in it and no return type.

37 of 53

Default Constructor

  • The default constructor is the constructor which doesn't take any argument. It has no parameter but a programmer can write some initialization statement there.

38 of 53

  • #include <iostream>
  • using namespace std;
  • class Calc
  • {
  • public:
  • int val;
  • Calc()
  • {
  • val = 20;
  • }
  • };

  • int main()
  • {
  • Calc c1;
  • cout << c1.val;
  • }

39 of 53

Parameterized Constructor

  • A default constructor does not have any parameter, but programmers can add and use parameters within a constructor if required. This helps programmers to assign initial values to an object at the time of creation.

40 of 53

  • #include <iostream>
  • using namespace std;
  • class Calc
  • {
  • public:
  • int val2;
  • Calc(int x)
  • {
  • val2=x;
  • }
  • };
  • int main()
  • {
  • Calc c1(10);
  • Calc c2(20);
  • Calc c3(30);
  • cout << c1.val2;
  • cout << c2.val2;
  • cout << c3.val2;
  • }

41 of 53

Copy Constructor

  • C++ provides a special type of constructor which takes an object as an argument and is used to copy values of data members of one object into another object. In this case, copy constructors are used to declaring and initializing an object from another object.

  • Calc C2(C1); Or Calc C2 = C1;

42 of 53

  • class CopyCon
  • {
  • int a, b;
  • public:
  • CopyCon(int x, int y)
  • {
  • a = x; b = y;
  • cout << "\nHere is the initialization of Constructor";
  • }
  • void Display()
  • {
  • cout << "\nValues : \t" << a << "\t" << b;
  • } �};
  • int main()
  • {
  • CopyCon Object(30, 40); //Copy Constructor CopyCon Object2 = Object; Object.Display();
  • Object2.Display();
  • return 0;
  • }

43 of 53

Constructor Overloading/�Multiple constructors in a Class�

  • Constructor can be overloaded in a similar way as function overloading.
  • Overloaded constructors have the same name (name of the class) but different number of arguments.
  • Depending upon the number and type of arguments passed, specific constructor is called.

44 of 53

  1. Integer() { m=0;n=0;}
  2. Integer(int a, int b)

{m=a;n=b;}

  1. integer(integer &i)

{m=i.m;n=i.n}

1. receives no argument

2.receive two integer arguments.

3. receive one integer object as an argument.

  • Integer i1;
  • Integer i2(20,40);
  • Integer i3(i2);

or

integer i3=i2;

45 of 53

Destructors

46 of 53

Destructor

  • Destroy the objects that have been created by the constructor/ when they are no longer required.

  • Destructor have the same name as the class name but preceded by a tilde operator.

~ integer()

{

}

47 of 53

  • Destructors never takes any argument nor does it return any value.

  • It releases the memory space for future use.

  • When the closing braces of a scope is encountered, the destructor for each object in the scope are called.

  • Objects are destroyed in the reverse order of creation.

  • destructor can’t be overloaded.

48 of 53

C++ Destructor Example��

class ABC

{

public:

ABC ()

{

cout << "Hey look I am in constructor" << endl;

}

~ABC()

{

cout << "Hey look I am in destructor" << endl;

}

};

int main()

{

ABC cc1;

cout << "function main is terminating...." << endl;

return 0;

}

49 of 53

Output

  • Hey look I am in constructor
  • Function main is terminating....
  • Hey look I am in destructor

  • Note: more than one destructor can’t be used in a program. Only single destructor is allowed.

50 of 53

int count=0;

class alpha

{

public:

alpha()

{

count++;

cout<<count;

}

~alpha()

{

cout<<count;

count--;

}

};

int main()

{

alpha a1,a2,a3,a4;

{

alpha a5;

}

{

alpha a6;

}

return 0;

}

51 of 53

Output

  • 1
  • 2
  • 3
  • 4

  • 5
  • 5

  • 5
  • 5

  • 4
  • 3
  • 2
  • 1

52 of 53

class ABC {

private:

int x,y;

public:

ABC ()

{

x = y = 0;

}

ABC(int a)

{

x = y = a;

}

ABC(int a,int b)

{

x = a; y = b;

}

void display()

{

cout << "x = " << x << " and " << "y = " << y << endl;

}

};

int main()

{

ABC cc1;

ABC cc2(10);

ABC cc3(10,20);

cc1.display();

cc2.display();

cc3.display();

return 0;

}

53 of 53

Output

  • x = 0 and y = 0
  • x = 10 and y = 10
  • x = 10 and y = 20