C ++ Unit-Ii

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

II - UNIT C++

C++ Object and Class


Object
 In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
 In other words, object is an entity that has state and behavior. Here, state means data and behavior
means functionality.
 Object is a runtime entity, it is created at runtime.
 Object is an instance of a class. All the members of the class can be accessed through object.
 Student s1; //creating an object of Student

Class
In C++, class is a group of similar objects.

It is a template from which objects are created. It can have fields, methods, constructors etc.

1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }

C++ Object and Class Example


1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
15. }

Output:

201
Sonoo Jaiswal

C++ Class Example: Initialize and Display data through method


1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }

Output:

201 Sonoo
202 Nakul
C++ Class Example: Store and Display Employee Information
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }

Output:

201 Sonoo 990000


202 Nakul 29000

C++ Class Member Functions


A class member function is a function that, like any other variable, is defined or prototyped within the class
declaration.
It has access to all the members of the class and can operate on any object of that class.

Let us use a member function to access the members of a previously created class instead of directly
accessing them.

1. class Dice {
2. public:
3. double L; // a dice's length
4. double B; // a dice's breadth
5. double H; // a dice's height
6. double getVolume(void); // Returns dice volume
7. };

Member functions can be defined either within the class definition or separately with the scope resolution
operator,:.

Even if the inline specifier is not used, specifying a member function within the class declaration declares
the function inline. So, you may either define the Volume() function as shown below.

1. class Dice {
2. public:
3. double L; // a dice's length
4. double B; // a dice's breadth
5. double H; // a dice's height
6. double getVolume(void) {
7. return L * B * H;
8. }
9. };

If we want, we may define the identical function outside of the class using the scope resolution operator
(::), as seen below.

1. double Dice::getVolume(void) {
2. return L * B * H;
3. }

The main thing to remember here is that we must use the class name exactly before the :: operator. The dot
operator (.) will be used to perform a member function on an object and will only manipulate data relevant
to that object as follows:

1. Dice myDice; // Generate an object


2. myDice.getVolume(); // Call the object's member function

C++ Program:
1. #include <iostream>
2. using namespace std;
3. class Dice {
4. public:
5. double L; // a dice's length
6. double B; // a dice's breadth
7. double H; // a dice's height
8. // Member functions declaration
9. double getVolume(void);
10. void setL(double length);
11. void setB(double breadth);
12. void setH(double height);
13. };
14. // Member functions definitions
15. double Dice::getVolume(void) {
16. return L * B * H;
17. }
18. void Dice::setL(double length)
19. {
20. L = length;
21. }
22. void Dice::setB(double breadth) {
23. B = breadth;
24. }
25. void Dice::setH(double height) {
26. H = height;
27. }
28. // Main function
29. int main() {
30. Dice Dice1; // Declare Dice1 of type Dice
31. Dice Dice2; // Declare Dice2 of type Dice
32. double volume = 0.0; // here the volume of a Dice is stored
33. // dice 1 specification
34. Dice1.setL(6.0);
35. Dice1.setB(7.0);
36. Dice1.setH(5.0);
37. // Dice 2 specification
38. Dice2.setL(12.0);
39. Dice2.setB(13.0);
40. Dice2.setH(10.0);
41. // volume of Dice 1
42. volume = Dice1.getVolume();
43. cout << "Volume of Dice1 : " << volume <<endl;
44. // volume ofDice 2
45. volume = Dice2.getVolume();
46. cout << "Volume of Dice2 : " << volume <<endl;
47. return 0;
48. }

Output:

Volume of Dice1 : 210


Volume of Dice2 : 1560

Static Member Function in C++


The static is a keyword in the C and C++ programming language. We use the static keyword to define the
static data member or static member function inside and outside of the class.

Static data member


When we define the data member of a class using the static keyword, the data members are called the static
data member.

A static data member is similar to the static member function because the static data can only be accessed
using the static data member or static member function.

And, all the objects of the class share the same copy of the static member to access the static data.

Syntax

1. static data_type data_member;

Here, the static is a keyword of the predefined library.

The data_type is the variable type in C++, such as int, float, string, etc.

The data_member is the name of the static data.

Example 1: Let's create a simple program to access the static data members in the C++ programming
language.

1. #include <iostream>
2. #include <string.h>
3. using namespace std;
4. // create class of the Car
5. class Car
6. {
7. private:
8. int car_id;
9. char car_name[20];
10. int marks;
11.
12. public:
13. // declare a static data member
14. static int static_member;
15. Car()
16. {
17. static_member++;
18. }
19. void inp()
20. {
21. cout << " \n\n Enter the Id of the Car: " << endl;
22. cin >> car_id; // input the id
23. cout << " Enter the name of the Car: " << endl;
24. cin >> car_name;
25. cout << " Number of the Marks (1 - 10): " << endl;
26. cin >> marks;
27. }
28. // display the entered details
29. void disp ()
30. {
31. cout << " \n Id of the Car: " << car_id;
32. cout << "\n Name of the Car: " << car_name;
33. cout << " \n Marks: " << marks;
34. }
35. };
36. // initialized the static data member to 0
37. int Car::static_member = 0;

38. int main ()


39. {
40. // create object for the class Car
41. Car c1;
42. // call inp() function to insert values
43. c1. inp ();
44. c1. disp();
45. //create another object
46. Car c2;
47. // call inp() function to insert values
48. c2. inp ();
49. c2. disp();
50. cout << " \n No. of objects created in the class: " << Car :: static_member <<endl;
51. return 0;
52. }

Output

Enter the Id of the Car:


101
Enter the name of the Car:
Ferrari
Number of the Marks (1 - 10):
10

Id of the Car: 101


Name of the Car: Ferrari
Marks: 10

Enter the Id of the Car:


205
Enter the name of the Car:
Mercedes
Number of the Marks (1 - 10):
9

Id of the Car: 205


Name of the Car: Mercedes
Marks: 9
No. of objects created in the class: 2

Static Member Functions


The static member functions are special functions used to access the static data members or other static
member functions. A member function is defined using the static keyword.

A static member function shares the single copy of the member function to any number of the class' objects.
We can access the static member function using the class name or class' objects.

If the static member function accesses any non-static data member or non-static member function, it throws
an error.

Syntax

1. class_name::function_name (parameter);

Here, the class_name is the name of the class.

function_name: The function name is the name of the static member function.

parameter: It defines the name of the pass arguments to the static member function.
Example 2: Let's create another program to access the static member function using the class name in the
C++ programming language.

1. #include <iostream>
2. using namespace std;
3. class Note
4. {
5. // declare a static data member
6. static int num;
7. public:
8. // create static member function
9. static int func ()
10. {
11. return num;
12. }
13. };
14. // initialize the static data member using the class name and the scope resolution operato
15. int Note :: num = 5;
16. int main ()
17. {
18. // access static member function using the class name and the scope resolution
19. cout << " The value of the num is: " << Note:: func () << endl;
20. return 0;
21. }

Output

The value of the num is: 5


Array of Objects in c++
 Like array of other user-defined data types, an array of type class can also be created.
 The array of type class contains the objects of the class as its individual elements.
 Thus, an array of a class type is also known as an array of objects.
 An array of objects is declared in the same way as an array of any built-in data type.

Syntax:
class_name array_name [size] ;

Example:
#include <iostream>

class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};

void main()
{
MyClass obs[4];
int i;

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


obs[i].setX(i);

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


cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n";

getch();
}

Output:
obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3
C++ Friend function
If a function is defined as a friend function in C++, then the protected and private data of a class can be
accessed using the function.

By using the keyword friend compiler knows the given function is a friend function.

For accessing the data, the declaration of a friend function should be done inside the body of a class starting
with the keyword friend.

Declaration of friend function in C++


1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };

Characteristics of a Friend function:

o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot membership operator with
the member name.
o It can be declared either in the private or the public part.

C++ friend function Example


1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }

Output:

Length of box: 10

simple example when the function is friendly to two classes.

1. #include <iostream>
2. using namespace std;
3. class B; // forward declarartion.
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i)
9. {
10. x=i;
11. }
12. friend void min(A,B); // friend function.
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. std::cout << a.x << std::endl;
28. else
29. std::cout << b.y << std::endl;
30. }
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }

Output:

10

In the above example, min() function is friendly to two classes, i.e., the min() function can access the private
members of both the classes A and B.

C++ Friend class


A friend class can access both private and protected members of the class in which it has been declared as
friend.

Let's see a simple example of a friend class.

1. #include <iostream>
2.
3. using namespace std;
4.
5. class A
6. {
7. int x =5;
8. friend class B; // friend class.
9. };
10. class B
11. {
12. public:
13. void display(A &a)
14. {
15. cout<<"value of x is : "<<a.x;
16. }
17. };
18. int main()
19. {
20. A a;
21. B b;
22. b.display(a);
23. return 0;
24. }

Output:

value of x is : 5

In the above example, class B is declared as a friend inside the class A. Therefore, B is a friend of class A.
Class B can access the private members of class A.

C++ Overloading (Function and Operator)


If we create two or more members having the same name but different in number or type of parameter, it
is known as C++ overloading. In C++, we can overload:

o methods,
o constructors, and
o indexed properties

It is because these members have parameters only.

Types of overloading in C++ are:


o Function overloading
o Operator overloading

C++ Function Overloading


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.

C++ Function Overloading Example


Let's see the simple example of function overloading where we are changing number of arguments of add()
method.

// program of function overloading when number of arguments vary.

1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. static int add(int a,int b){
6. return a + b;
7. }
8. static int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12. };
13. int main(void) {
14. Cal C; // class object declaration.
15. cout<<C.add(10, 20)<<endl;
16. cout<<C.add(12, 20, 23);
17. return 0;
18. }

Output:

30
55

// Program of function overloading with different types of arguments.

1. #include<iostream>
2. using namespace std;
3. int mul(int,int);
4. float mul(float,int);
5. int mul(int a,int b)
6. {
7. return a*b;
8. }
9. float mul(double x, int y)
10. {
11. return x*y;
12. }
13. int main()
14. {
15. int r1 = mul(6,7);
16. float r2 = mul(0.2,3);
17. std::cout << "r1 is : " <<r1<< std::endl;
18. std::cout <<"r2 is : " <<r2<< std::endl;
19. return 0;
20. }

Output:

r1 is : 42
r2 is : 0.6

Function Overloading and Ambiguity


When the compiler is unable to decide which function is to be invoked among the overloaded function, this
situation is known as function overloading.

When the compiler shows the ambiguity error, the compiler does not run the program.

Causes of Function Overloading:

o Type Conversion.
o Function with default arguments.
o Function with pass by reference.

o Type Conversion:
Let's see a simple example.

1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(float);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(float j)
10. {
11. std::cout << "Value of j is : " <<j<< std::endl;
12. }
13. int main()
14. {
15. fun(12);
16. fun(1.2);
17. return 0;
18. }

o Function with Default Arguments

1. #include<iostream>
2. using namespace std;
3. void fun(int);
4. void fun(int,int);
5. void fun(int i)
6. {
7. std::cout << "Value of i is : " <<i<< std::endl;
8. }
9. void fun(int a,int b=9)
10. {
11. std::cout << "Value of a is : " <<a<< std::endl;
12. std::cout << "Value of b is : " <<b<< std::endl;
13. }
14. int main()
15. {
16. fun(12);
17.
18. return 0;
19. }

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:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Syntax of Operator Overloading

1. return_type class_name : : operator op(argument_list)


2. {
3. // body of the function.
4. }

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

o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member function can be
used to overload those operators.
o 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.
o 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


// program to overload the unary operator ++.

1. #include <iostream>
2. using namespace std;
3. class Test
4. {
5. private:
6. int num;
7. public:
8. Test(): num(8){}
9. void operator ++() {
10. num = num+2;
11. }
12. void Print() {
13. cout<<"The Count is: "<<num;
14. }
15. };
16. int main()
17. {
18. Test tt;
19. ++tt; // calling of a function "void operator ++()"
20. tt.Print();
21. return 0;
22. }

Output:

The Count is: 10

C - Bit Fields
Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status,
as follows −
struct {
unsigned int widthValidated;
unsigned int heightValidated;
} status;
This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1 in each of
the variables. The C programming language offers a better way to utilize the memory space in such
situations.
If you are using such variables inside a structure then you can define the width of a variable which tells the
C compiler that you are going to use only those number of bytes. For example, the above structure can be
re-written as follows −
struct {
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be used to
store the values.
If you will use up to 32 variables each one with a width of 1 bit, then also the status structure will use 4
bytes. However as soon as you have 33 variables, it will allocate the next slot of the memory and it will
start using 8 bytes. Let us check the following example to understand the concept −
Live Demo
#include <stdio.h>
#include <string.h>

/* define simple structure */


struct {
unsigned int widthValidated;
unsigned int heightValidated;
} status1;

/* define a structure with bit fields */


struct {
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status2;

int main( ) {
printf( "Memory size occupied by status1 : %d\n", sizeof(status1));
printf( "Memory size occupied by status2 : %d\n", sizeof(status2));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by status1 : 8
Memory size occupied by status2 : 4

Bit Field Declaration


The declaration of a bit-field has the following form inside a structure −
struct {
type [member_name] : width ;
};
Sr.No. Element & Description

1
type
An integer type that determines how a bit-field's value is interpreted. The type may be int, signed int,
or unsigned int.

2
member_name
The name of the bit-field.

3
width
The number of bits in the bit-field. The width must be less than or equal to the bit width of the
specified type.

Live Demo
#include <stdio.h>
#include <string.h>

struct {
unsigned int age : 3;
} Age;

int main( ) {

Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );

Age.age = 7;
printf( "Age.age : %d\n", Age.age );

Age.age = 8;
printf( "Age.age : %d\n", Age.age );

return 0;
}
When the above code is compiled it will compile with a warning and when executed, it produces the
following result −
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
Age.age : 0
Constructor in C++?
A constructor is a particular member function having the same name as the class name. It calls
automatically whenever the object of the class is created.

Syntax:
The syntax of the constructor in C++ are given below.

1. class class_name
2. {
3. ……….
4. public
5. class_name ([parameter list])
6. {
7. ……………….
8. }
9. };

In the above-given syntax, class_name is the constructor's name, the public is an access specifier, and the
parameter list is optional.

Example of Constructor:
1. #include <iostream.h>
2. #include <conio.h>
3. using namespace std;
4. class hello { // The class
5. public: // Access specifier
6. hello () { // Constructor
7. cout << "Hello World! Program in C++ by using Constructor";
8. }
9. void display() {
10. cout <<"Hello World!" <<endl;
11. }
12. };
13. int main() {
14. hello myObj; /
15. return 0;
16. }
There are four types of constructors used in C++.

o Default constructor
o Dynamic constructor
o Parameterized constructor
o Copy constructor

Default Constructor: A constructor is a class which accepts no parameter and is called a default
constructor. If there is no constructor for a class, the compiler implicitly creates a default constructor.

Following is the syntax of the default constructor:

1. class class_name {
2. private:
3. ………..
4. ………..
5. public:
6. class_name ()
7. {
8. …….
9. }
10. }

In this type of constructor, there are no arguments and parameter lists.

If no constructor is defined in the class, the compiler automatically creates the class's default constructor.

Example:

1. class student {
2. private:
3. ………..
4. ………..
5. public:
6. student ()
7. {
8. …….
9. }
10. }

The default constructor for a class student is given below:


hello::hello()

Parameterised Constructor: A constructor is a class that can take parameters and is called a parameterized
constructor. It is used to initialize objects with a different set of values.

Syntax of the Parameterised constructor is given below.

1. Class classname
2. {
3. …………;
4. …………;
5. Public:
6. Class name (parameter list)
7. {
8. ………….;
9. }
10. };

Here, we can define the parameter list of the constructor.

Copy Constructor: A particular constructor used for the creation of an existing object. The copy
constructor is used to initialize the thing from another of the same type.

Syntax:

Syntax of the copy constructor is given below.

1. Class (classname, &object)


2. {
3. ………….;
4. ………….;
5. }

In the above syntax, the object refers to a thing used to initialize another object.

Dynamic Constructor: This type of constructor can be used to allocate the memory while creating the
objects. The data members of an object after creation can be initialized, called dynamic initialization.
Destructor in C++?
Destructors have the same class name preceded by (~) tilde symbol. It removes and destroys the memory
of the object, which the constructor allocated during the creation of an object.

Syntax:
The syntax of destructor in C++ are given below.

1. class class_name
2. {
3. …………….;
4. …………….;
5. public:
6. xyz(); //constructor
7. ~xyz(); //destructor
8. };

The Destructor has no argument and does not return any value, so it cannot be overloaded.

Example of Destructor:
1. #include <iostream.h>
2. #include <conio.h>
3. using namespace std;
4. class Hello {
5. public:
6. //Constructor
7. Hello () {
8. cout<< "Constructor function is called" <<endl;
9. }
10. //Destructor
11. ~Hello () {
12. cout << "Destructor function is called" <<endl;
13. }
14. //Member function
15. void display() {
16. cout <<"Hello World!" <<endl;
17. }
18. };
19. int main(){
20. //Object created
21. Hello obj;
22. //Member function called
23. obj.display();
24. return 0;
25. }

Difference between Constructor and Destructor in C++


programming

Basis Constructor Destructor

Purpose of To allocate memory to the object, we used a To deallocate the memory that the constructor
use constructor in C++. allocated to an object for this purpose, we use the
concept of destructor in C++.

Arguments It may or may not contain arguments. It cannot contain the arguments.

Calling It is called automatically whenever the object of It is called automatically whenever the program
the class is created. terminates.

Memory Constructor occupies memory. The Destructor releases memory.

Return type It has return types. It doesn't have any return type.

Special While declaring constructor in the C++ While declaring a destructor in C++ programming
symbol programming language, there is no requirement of language, a particular symbol is required, i.e., tilde
the special symbol. symbol.

In numbers We can use more than one constructor in our We cannot use more than one destructor in the
program. program.

Inheritance It can be inherited. It cannot be inherited.

Overloading It can be overloaded. It cannot be overloaded.

Execution They are executed in successive order. They are executed in the constructor's reverse
Order order; basically, they are the inverse of the
constructors.
Types Constructor has four types: Destructors have no classes.

o Default constructor
o Copy constructor
o Parameterized constructor
o Dynamic constructor

Declaration The following declaration is used for creating a The following declaration is used for creating a
constructor: destructor:
class class_name class class_name
{ {
………. …………….;
public …………….;
class_name ([parameter list]) public:
{ ~xyz();
………………. {
} …………
}; };

You might also like