0% found this document useful (0 votes)
8 views74 pages

Unit 3&4 Inheritance, Polymorphism and Virtual Function

The document explains inheritance, polymorphism, and virtual functions in C++, highlighting the process of a derived class acquiring properties from a base class. It details the types of inheritance, including single, multiple, hierarchical, multilevel, and hybrid inheritance, along with their advantages and syntax. Additionally, it addresses visibility modes and ambiguity resolution in inheritance scenarios.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views74 pages

Unit 3&4 Inheritance, Polymorphism and Virtual Function

The document explains inheritance, polymorphism, and virtual functions in C++, highlighting the process of a derived class acquiring properties from a base class. It details the types of inheritance, including single, multiple, hierarchical, multilevel, and hybrid inheritance, along with their advantages and syntax. Additionally, it addresses visibility modes and ambiguity resolution in inheritance scenarios.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

Unit 3&4.

Inheritance ,Polymorphism and


Virtual Function.
In C++, inheritance is a process in which one object acquires all the
properties and behaviors of its parent object automatically. In such way, you can
reuse, extend or modify the attributes and behaviors which are defined in other
class.

In C++, the class which inherits the members of another class is called derived
class and the class whose members are inherited is called base class. The derived
class is the specialized class for the base class.

Concepts of inheritance:-
 Inheritance is another important feature of Object Oriented Programming.
 Inheritance gives you the way to use already existing classes into the new class rather
than writing existing class code again into new class.
 The mechanism of deriving a new class from an old class is called Inheritance.
 The old class is referred as base class and new class is referred as Derived class.
 The derived class inherits some or all the properties from the base class.

Base
class

Derived
class
Fig. inheritance
Advantage of C++ Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there
is no need to define the member again. So less code is required in the class.

Types Of Inheritance
C++ supports five types of inheritance:

o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance

Derived Classes
A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

1. class derived_class_name :: visibility-mode base_class_name


2. {
3. // body of the derived class.
4. }

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base
class are publicly inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

o When the base class is privately inherited by the derived class, public
members of the base class becomes the private members of the derived
class. Therefore, the public members of the base class are not accessible by
the objects of the derived class only by the member functions of the derived
class.
o When the base class is publicly inherited by the derived class, public
members of the base class also become the public members of the derived
class. Therefore, the public members of the base class are accessible by the
objects of the derived class as well as by the member functions of the base
class.

Note:

o In C++, the default mode of visibility is private.


o The private members of the base class are never inherited.

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class is
inherited from the only one base class.
Where 'A' is the base class, and 'B' is the derived class.

C++ Single Level Inheritance Example: Inheriting Fields


When one class inherits another class, it is known as single level inheritance. Let's
see the example of single level inheritance which inherits the fields only.

1. #include <iostream>
2. using namespace std;
3. class Account {
4. public:
5. float salary = 60000;
6. };
7. class Programmer: public Account {
8. public:
9. float bonus = 5000;
10. };
11. int main(void) {
12. Programmer p1;
13. cout<<"Salary: "<<p1.salary<<endl;
14. cout<<"Bonus: "<<p1.bonus<<endl;
15. return 0;
16. }

Output:

Salary: 60000
Bonus: 5000

In the above example, Employee is the base class and Programmer is


the derived class.

C++ Single Level Inheritance Example: Inheriting Methods


Let's see another example of inheritance in C++ which inherits methods only.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking...";
14. }
15. };
16. int main(void) {
17. Dog d1;
18. d1.eat();
19. d1.bark();
20. return 0;
21. }

Output:

Eating...
Barking...

Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. int a = 4;
6. int b = 5;
7. public:
8. int mul()
9. {
10. int c = a*b;
11. return c;
12. }
13. };
14.
15. class B : private A
16. {
17. public:
18. void display()
19. {
20. int result = mul();
21. std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
22. }
23. };
24. int main()
25. {
26. B b;
27. b.display();
28.
29. return 0;
30. }

Output:

Multiplication of a and b is : 20

In the above example, class A is privately inherited. Therefore, the mul() function of
class 'A' cannot be accessed by the object of class B. It can only be accessed by the
member function of class B.

How to make a Private Member Inheritable


The private member is not inheritable. If we modify the visibility mode by making it
public, but this takes away the advantage of data hiding.

C++ introduces a third visibility modifier, i.e., protected. The member which is
declared as protected will be accessible to all the member functions within the
class as well as the class immediately derived from it.

Visibility modes can be classified into three categories:


Base class visibility Derived class visibility

Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected

o Public: When the member is declared as public, it is accessible to all the


functions of the program.
o Private: When the member is declared as private, it is accessible within the
class only.
o Protected: When the member is declared as protected, it is accessible within
its own class as well as the class immediately derived from it.

Visibility of Inherited Members


C++ Multilevel Inheritance
Multilevel inheritance is a process of deriving a class from another derived class.
C++ Multi Level Inheritance Example
When one class inherits another class which is further inherited by another class, it
is known as multi level inheritance in C++. Inheritance is transitive so the last
derived class acquires all the members of all its base classes.

Let's see the example of multi level inheritance in C++.

1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat() {
6. cout<<"Eating..."<<endl;
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void bark(){
13. cout<<"Barking..."<<endl;
14. }
15. };
16. class BabyDog: public Dog
17. {
18. public:
19. void weep() {
20. cout<<"Weeping...";
21. }
22. };
23. int main(void) {
24. BabyDog d1;
25. d1.eat();
26. d1.bark();
27. d1.weep();
28. return 0;
29. }

Output:

Eating...
Barking...
Weeping...

C++ Multiple Inheritance


Multiple inheritance is the process of deriving a new class that inherits the
attributes from two or more classes.

Syntax of the Derived class:

1. class D : visibility B-1, visibility B-2, ?


2. {
3. // Body of the class;
4. }
Let's see a simple example of multiple inheritance.

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a(int n)
9. {
10. a = n;
11. }
12. };
13.
14. class B
15. {
16. protected:
17. int b;
18. public:
19. void get_b(int n)
20. {
21. b = n;
22. }
23. };
24. class C : public A,public B
25. {
26. public:
27. void display()
28. {
29. std::cout << "The value of a is : " <<a<< std::endl;
30. std::cout << "The value of b is : " <<b<< std::endl;
31. cout<<"Addition of a and b is : "<<a+b;
32. }
33. };
34. int main()
35. {
36. C c;
37. c.get_a(10);
38. c.get_b(20);
39. c.display();
40.
41. return 0;
42. }

Output:

The value of a is : 10
The value of b is : 20
Addition of a and b is : 30

In the above example, class 'C' inherits two base classes 'A' and 'B' in a public
mode.

Ambiquity Resolution in Inheritance


Ambiguity can be occurred in using the multiple inheritance when a function with
the same name occurs in more than one base class.

Let's understand this through an example:

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. void display()
7. {
8. std::cout << "Class A" << std::endl;
9. }
10. };
11. class B
12. {
13. public:
14. void display()
15. {
16. std::cout << "Class B" << std::endl;
17. }
18. };
19. class C : public A, public B
20. {
21. void view()
22. {
23. display();
24. }
25. };
26. int main()
27. {
28. C c;
29. c.display();
30. return 0;
31. }

Output:

error: reference to 'display' is ambiguous


display();

o The above issue can be resolved by using the class resolution operator with
the function. In the above example, the derived class code can be rewritten
as:

1. class C : public A, public B


2. {
3. void view()
4. {
5. A :: display(); // Calling the display() function of class A.
6. B :: display(); // Calling the display() function of class B.
7.
8. }
9. };
An ambiguity can also occur in single inheritance.

Consider the following situation:

1. class A
2. {
3. public:
4. void display()
5. {
6. cout<<?Class A?;
7. }
8. } ;
9. class B
10. {
11. public:
12. void display()
13. {
14. cout<<?Class B?;
15. }
16. };

In the above case, the function of the derived class overrides the method of the
base class. Therefore, call to the display() function will simply call the function
defined in the derived class. If we want to invoke the base class function, we can
use the class resolution operator.

1. int main()
2. {
3. B b;
4. b.display(); // Calling the display() function of B class.
5. b.B :: display(); // Calling the display() function defined in B class.
6. }

C++ Hybrid Inheritance


Hybrid inheritance is a combination of more than one type of inheritance.
Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. protected:
6. int a;
7. public:
8. void get_a()
9. {
10. std::cout << "Enter the value of 'a' : " << std::endl;
11. cin>>a;
12. }
13. };
14.
15. class B : public A
16. {
17. protected:
18. int b;
19. public:
20. void get_b()
21. {
22. std::cout << "Enter the value of 'b' : " << std::endl;
23. cin>>b;
24. }
25. };
26. class C
27. {
28. protected:
29. int c;
30. public:
31. void get_c()
32. {
33. std::cout << "Enter the value of c is : " << std::endl;
34. cin>>c;
35. }
36. };
37.
38. class D : public B, public C
39. {
40. protected:
41. int d;
42. public:
43. void mul()
44. {
45. get_a();
46. get_b();
47. get_c();
48. std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
49. }
50. };
51. int main()
52. {
53. D d;
54. d.mul();
55. return 0;
56. }
Output:

Enter the value of 'a' :


10
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000

C++ Hierarchical Inheritance


Hierarchical inheritance is defined as the process of deriving more than one class
from a base class.

Syntax of Hierarchical inheritance:

1. class A
2. {
3. // body of the class A.
4. }
5. class B : public A
6. {
7. // body of class B.
8. }
9. class C : public A
10. {
11. // body of class C.
12. }
13. class D : public A
14. {
15. // body of class D.
16. }

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class Shape // Declaration of base class.
4. {
5. public:
6. int a;
7. int b;
8. void get_data(int n,int m)
9. {
10. a= n;
11. b = m;
12. }
13. };
14. class Rectangle : public Shape // inheriting Shape class
15. {
16. public:
17. int rect_area()
18. {
19. int result = a*b;
20. return result;
21. }
22. };
23. class Triangle : public Shape // inheriting Shape class
24. {
25. public:
26. int triangle_area()
27. {
28. float result = 0.5*a*b;
29. return result;
30. }
31. };
32. int main()
33. {
34. Rectangle r;
35. Triangle t;
36. int length,breadth,base,height;
37. std::cout << "Enter the length and breadth of a rectangle: " << std::
endl;
38. cin>>length>>breadth;
39. r.get_data(length,breadth);
40. int m = r.rect_area();
41. std::cout << "Area of the rectangle is : " <<m<< std::endl;
42. std::cout << "Enter the base and height of the triangle: " << std::en
dl;
43. cin>>base>>height;
44. t.get_data(base,height);
45. float n = t.triangle_area();
46. std::cout <<"Area of the triangle is : " << n<<std::endl;
47. return 0;
48. }

Output:

Enter the length and breadth of a rectangle:


23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5

Overriding Member Function:


In Object-oriented programming, Inheritance is one of the most powerful concepts.
It enables a class to inherit characteristics and behaviors from another class.
Overriding is a technique used in C++ programming to modify the behavior of an
inherited member function in a derived class. In this article, we will see the concept
of Overriding Member functions in C++ in detail.
What is Overriding Member Function?
In C++, when a Derived class inherits a Member function from its Base class, it can
redefine the behavior of that function in the Derived class. This process of
redefining a Base class Member Function in a Derived class is called "Overriding"
and the redefined function is referred to as an "Overridden Member Function".

In other words, when a Derived class defines a Member Function with the same
name and signature as a Member Function in its Base class, the Derived class's
function will Override the Base class function.

How to Override a Member Function in C++?


To Override a Member Function in C++, we need to follow the steps given below:

Step 1: Define a Base Class with a Virtual Function:

A Virtual Function is a type of member function declared with the keyword


"Virtual" in the base class. This indicates that the function can be Overridden in
the derived class. The syntax for declaring a Virtual Function is as follows:

C++ code:

1. class Base {
2. public:
3. virtual void myFunction() {
4. // Base class implementation
5. }
6. };

Step 2: Define a Derived Class that Overrides the Virtual Function:


To Override a Virtual Function, we need to define a derived class that inherits
from the base class and provides a new implementation of the Virtual Function.
The syntax for defining a derived class that overrides the Virtual Function is as
follows:

C++ Code:

1. class Derived : public Base {


2. public:
3. void myFunction() override {
4. // Derived class implementation
5. }
6. };

Step 3: Create Objects of the Derived Class and Call the Virtual
Function:
We can create objects of the derived class and call the Virtual Function using
a Pointer to the base class. The syntax for creating objects of the derived class
and calling the Virtual Function is as follows:

C++ Code:

1. Base* basePtr = new Derived();


2. basePtr->myFunction();
or
base *basePtr
Derived d1;
basePtr=&d1;
basePtr-> myFunction();

When we call the Virtual Function using a Pointer to the base class, the
implementation of the Virtual Function in the derived class will be called.

Example:

Let's look at an example that demonstrates the concept of Overriding Member


Functions in C++. In the above example, we have a base class or parent class
called, which has a virtual function. We also have two derived classes called Circle
and Square, which override the draw() function to provide their own
implementation.

C++ Code:

1. #include <iostream>
2. class Shape {
3. public:
4. virtual void draw() {
5. std::cout << "Drawing a shape" << std::endl;
6. }
7. };
8.
9. class Circle : public Shape {
10.public:
11. void draw() override {
12. std::cout << "Drawing a circle" << std::endl;
13. }
14.};
15.
16.class Square : public Shape {
17. public:
18. void draw() override {
19. std::cout << "Drawing a square" << std::endl;
20. }
21. };
22.
23. int main() {
24. //Shape* shapePtr = new Circle();
25. Shape* shapePtr;
26. Circle c1;
27. shapePtr=&c1;
28. shapePtr->draw();
29.
30. shapePtr = new Square();
31. shapePtr->draw();
32.
33. return 0;
34. }

Output:

Drawing a circle
Drawing a square

In this example, we create objects of the Circle and Square classes and call
the draw() function using a pointer to the base class Shape. Since the draw()
function is Virtual, the implementation in the derived classes is called, and we get
the output "Drawing a circle" and "Drawing a square".

Advantages of Overriding Member Function:


Polymorphism:

One of the major advantages of overriding is that it enables Polymorphism.


Polymorphism allows a derived class to have multiple behaviors depending on the
context in which it is used.

Code Reusability:

Overriding allows the reuse of code from the base class while allowing the derived
class to modify the behavior of the base class's member functions.

Modularity:

Overriding makes it easier to maintain code because changes made in the derived
class do not affect the base class.

Rules for Overriding Member Functions:


o The Overridden Function in the derived class must have the same name and
arguments as the base class function.
o The Overridden Function must have the same return type as the base class function
or a covariant return type.
o The access level of the Overridden Function in the derived class cannot be more
restrictive than the access level of the base class function.
o The Virtual keyword must be used in the base class function declaration.
o The function in the base class must be declared with the same access level or higher
than the derived class.

Operator Overloading:
Operator overloading is the mechanism to give special meaning to an operator for the different
data type.
We can give the special meaning to an operator but we are not going to change the basic
meaning of an operator.

To overload the operator we have a special operator function operator() in C++.

Syntax of declaring operator Function inside class: -

<return type> operator op(argument list);

Defining operator Function outside class: -

<return type> <class name>:: operator op(arguments list)

//code

 Here return type is the type of value return by the specified operation in the operator ().
 Operator is the keyword which tells to the compiler that it is a operator function.
 OP is the operator being overloaded.

Operator () function must be either member function or friend function but not
the static function of a class.

By using this operator function we can overload 2 types of operators:-


1) Unary Operator : ++,-- (Requires only one operand) Ex: a++
2) Binary Operator :+,-,*,/ (Requires Two Operands) Ex: a + b
Rules for operator overloading: -

1) Only existing operators can be overloaded.


2) New operators cannot be created.
3) We cannot change the basic meaning of an operator.
4) The overloaded operator must have at least one operand.
5) Overloaded operator follows the syntax & rules of original operators.
6) Unary and binary operators overloaded using member function as well as friend
function of a class.
7) Following operators cannot be
overloaded- 1] pointer to member ( , .*)

2] Scope Resolution Operator (::)

3) Conditional Operator ( ?)

4) Size Of Operator ( sizeof() )

5) Membership Operator (.)

Function No of arguments required

Unary Binary

Member Function No arguments One explicit argument (01)

Friend Function One reference argument ( 01) Two explicit operator (02)

1. Unary operator Overloading:-

 The unary operators operate on a single operand and following are the examples of
Unary operators −
o The increment (++) and decrement (--) operators.
o The unary minus (-) operator.
o The logical not (!) operator.
 The unary operators operate on the object for which they were called and normally,
this operator appears on the left side of the object, as in !obj, -obj, and ++obj but
sometime they can be used as postfix as well like obj++ or obj--.
 Following example explain how minus (-) operator can be overloaded for prefix as
well as postfix usage
1)
Class data

int

x,y,z;

public:

void accept()

cout<<”Enter x,y,z

value”; cin>>x>>y>>z;

void display()

cout<<x<<y<<z;

void operator -();

};

void data :: operator –()


{

x = -x;

y = -y;

z= -z;

void main()

Data D1;

D1.accept
();

-D1; //Call Operator –()

Function D1.display();

}
2)

#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};

int main() {
Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation


D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

return 0;
}

When the above code is compiled and executed, it produces the


following result −

F: -11 I:-10

F: 5 I:-11

The increment (++) and decrement (--) operators are two important
unary operators available in C++.

Following example explain how increment (++) operator can be


overloaded for prefix as well as postfix usage. Similar way, you can
overload operator (--).

#include <iostream>
using namespace std;

class Time {
private:
int hours; // 0 to 23
int minutes; // 0 to 59

public:
// required constructors
Time() {
hours = 0;
minutes = 0;
}
Time(int h, int m) {
hours = h;
minutes = m;
}

// method to display time


void displayTime() {
cout << "H: " << hours << " M:" << minutes <<endl;
}

// overloaded prefix ++ operator


Time operator++() {
++minutes; // increment this object
if(minutes >= 60) {
++hours;
minutes -= 60;
}
return Time(hours, minutes);
}

// overloaded postfix ++ operator


Time operator++( int ) {
// save the orignal value
Time T(hours, minutes);

// increment this object


++minutes;

if(minutes >= 60) {


++hours;
minutes -= 60;
}

// return old original value


return T;
}
};

int main() {
Time T1(11, 59), T2(10,40);

++T1; // increment T1
T1.displayTime(); // display T1
++T1; // increment T1 again
T1.displayTime(); // display T1

T2++; // increment T2
T2.displayTime(); // display T2
T2++; // increment T2 again
T2.displayTime(); // display T2
return 0;
}

When the above code is compiled and executed, it produces the


following result −

H: 12 M:0

H: 12 M:1

H: 10 M:41

H: 10 M:42

2. Binary Operator Overloading


Syntax of the Binary Operator Overloading

Following is the Binary Operator Overloading syntax in the C++ Programming


language.

return_type :: operator binary_operator_symbol (arg)

// function definition

return_type: It defines the return type of the function.

operator: It is a keyword of the function overloading.

binary_operator_symbol: It represents the binary operator symbol that


overloads a function to perform the calculation.

arg: It defines the argument passed to the function.


Binary operators work on two operands. For example,

result = num + 9;

Here, + is a binary operator that works on the num and 9.


operands
When we overload the binary operator for user-defined types by using the
code:

obj3 = obj1 + obj2;

The operator function is called using the obj1 object and obj2 is passed as an argument to
the function.

Example 1: Program to perform the addition and subtraction of two


complex numbers using the binary (+) and (-) operator

Let's create a program to calculate the addition and subtraction of two complex
numbers by overloading the '+' and '-' binary operators in the C++ programming
language.

/* use binary (+) operator to add two complex numbers. */

#include <iostream>

using namespace std;

class Complex_num

// declare data member or variables

int real, img;

public:
// create a member function to take input

void inp()

cout << " Input two complex number: " << endl;

cin >> real>> img;

// use binary '+' operator to overload

Complex_num operator + (Complex_num obj)

// create an object

Complex_num A;

// assign values to object

A.real = real + obj.real; //x1+y1 x1.+(y1)

A.img =img + obj.img;

return (A);

// overload the binary (-) operator

Complex_num operator - (Complex_num obj)

// create an object

Complex_num A;

// assign values to object

A.real = real - obj.real;

A.img= img- obj.img;


return (A);

// display the result of addition

void print()

cout << real<< " + " << img<< "i" << "\n";

// display the result of subtraction

void print2()

cout << real << " - " << img << "i" << "\n";

};

int main ()

Complex_num x1, y1, sum, sub; // here we created object of class Addition i.e x1 a
nd y1

// accepting the values

x1.inp();

y1.inp();

// add the objects

sum = x1 + y1;

sub = x1 - y1; // subtract the complex number

// display user entered values


cout << "\n Entered values are: \n";

cout << " \t";

x1.print();

cout << " \t";

y1.print();

cout << "\n The addition of two complex (real and imaginary) numbers: ";

sum.print(); // call print function to display the result of addition

cout << "\n The subtraction of two complex (real and imaginary) numbers: ";

sub.print2(); // call print2 function to display the result of subtraction

return 0;

Output

Input two complex numbers:

Input two complex numbers:

Entered values are:

5 + 7i

3 + 5i

The addition of two complex (real and imaginary) numbers: 8 + 12i

The subtraction of two complex (real and imaginary) numbers: 2 - 2i

2)
#include <iostream>
using namespace std;
class Distance
{
public:
// Member Object
int feet, inch;
// No Parameter Constructor
Distance()
{
this->feet = 0;
this->inch = 0;
}

// Constructor to initialize the object's value


// Parametrized Constructor
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}

// Overloading (+) operator to perform addition of


// two distance object
Distance operator+(Distance& d2) // Call by reference
{
// Create an object to return
Distance d3;

// Perform addition of feet and inches


d3.feet = this->feet + d2.feet;
d3.inch = this->inch + d2.inch;

// Return the resulting object


return d3;
}
};

// Driver Code
int main()
{
// Declaring and Initializing first object
Distance d1(8, 9);

// Declaring and Initializing second object


Distance d2(10, 2);

// Declaring third object


Distance d3;

// Use overloaded operator


d3 = d1 + d2;
// Display the result
cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch;
return 0;
}

Output:
Total Feet & Inches: 18'11

Data Conversion:-
Type Conversion in C++(type casting):-
In this topic, we will discuss the conversion of one data type into another in the
C++ programming language. Type conversion is the process that converts the
predefined data type of one variable into an appropriate data type. The main idea
behind type conversion is to convert two different data type variables into a single
data type to solve mathematical and logical expressions easily without any data
loss.

For example, we are adding two numbers, where one variable is of int type and
another of float type; we need to convert or typecast the int variable into a float
to make them both float data types to add them.

Type conversion can be done in two ways in C++, one is implicit type
conversion, and the second is explicit type conversion. Those conversions are
done by the compiler itself, called the implicit type or automatic type conversion.
The conversion, which is done by the user or requires user interferences called
the explicit or user define type conversion. Let's discuss the implicit and explicit
type conversion in C++.

Implicit Type Conversion


The implicit type conversion is the type of conversion done automatically by the
compiler without any human effort. It means an implicit conversion automatically
converts one data type into another type based on some predefined rules of the
C++ compiler. Hence, it is also known as the automatic type conversion.

For example:

1. int x = 20;
2. short int y = 5;
3. int z = x + y;

In the above example, there are two different data type variables, x, and y, where
x is an int type, and the y is of short int data type. And the resultant variable z is
also an integer type that stores x and y variables. But the C++ compiler
automatically converts the lower rank data type (short int) value into higher type
(int) before resulting the sum of two numbers. Thus, it avoids the data loss,
overflow, or sign loss in implicit type conversion of C++.

Order of the typecast in implicit conversion


The following is the correct order of data types from lower rank to higher rank:
1. bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long i
nt -> long long int -> float -> double -> long double

Program to convert int to float type using implicit type conversion


Let's create a program to convert smaller rank data types into higher types using
implicit type conversion.

Program1.cpp

1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // assign the integer value
6. int num1 = 25;
7. // declare a float variable
8. float num2;
9. // convert int value into float variable using implicit conversion
10. num2 = num1;
11. cout << " The value of num1 is: " << num1 << endl;
12. cout << " The value of num2 is: " << num2 << endl;
13. return 0;
14. }

Output

The value of num1 is: 25


The value of num2 is: 25

Program to convert double to int data type using implicit type


conversion
Let's create a program to convert the higher data type into lower type using
implicit type conversion.

Program2.cpp

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int num; // declare int type variable
6. double num2 = 15.25; // declare and assign the double variable
7.
8. // use implicit type conversion to assign a double value to int variable
9. num = num2;
10. cout << " The value of the int variable is: " << num << endl;
11. cout << " The value of the double variable is: " << num2 << endl;
12. return 0;
13. }

Output

The value of the int variable is: 15


The value of the double variable is: 15.25

In the above program, we have declared num as an integer type and num2 as the
double data type variable and then assigned num2 as 15.25. After this, we assign
num2 value to num variable using the assignment operator. So, a C++ compiler
automatically converts the double data value to the integer type before assigning
it to the num variable and print the truncate value as 15.

Explicit type conversion


Conversions that require user intervention to change the data type of one
variable to another, is called the explicit type conversion. In other words, an
explicit conversion allows the programmer to manually changes or typecasts the
data type from one variable to another type. Hence, it is also known as
typecasting. Generally, we force the explicit type conversion to convert data from
one type to another because it does not follow the implicit conversion rule.

The explicit type conversion is divided into two ways:

1. Explicit conversion using the cast operator


2. Explicit conversion using the assignment operator

Program to convert float value into int type using the cast operator
Cast operator: In C++ language, a cast operator is a unary operator who
forcefully converts one type into another type.
Let's consider an example to convert the float data type into int type using the
cast operator of the explicit conversion in C++ language.

Program3.cpp

1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. float f2 = 6.7;
6. // use cast operator to convert data from one type to another
7. int x = static_cast <int> (f2);
8. cout << " The value of x is: " << x;
9. return 0;
10. }

Output

The value of x is: 6

Program to convert one data type into another using the assignment
operator
Let's consider an example to convert the data type of one variable into another
using the assignment operator in the C++ program.

Program4.cpp

1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // declare a float variable
6. float num2;
7. // initialize an int variable
8. int num1 = 25;
9.
10. // convert data type from int to float
11. num2 = (float) num1;
12. cout << " The value of int num1 is: " << num1 << endl;
13. cout << " The value of float num2 is: " << num2 << endl;
14. return 0;
15. }

Output

The value of int num1 is: 25


The value of float num2 is: 25.0

Polymorphism -

 The word polymorphism is derived from the greek meaning many forms.
 It allows a single name to be used for more than one related purposes which
are technically different. One Thing for Many Purposes/Forms.

Polymorphism

COMPILE-TIME RUN-TIME
POLYMORPHISM POLYMORPHISM

FUNCTION Ov OPERATOR VIRTUAL


ERLOADING OVERLOADING FUNCTION

Polymorphism is categorized into two types-


1] Compile-time polymorphism
2] Run-time polymorphism
1] Compile-Time Polymorphism-
The concept of polymorphism is implemented by using the overloaded function and
operators.
In function or operator overloading the complier decides which function to call and
pass an argument to function these all are done at compile time so this is compile time
polymorphism. It is also called as early/static binding.

1. Function Overloading
 Overloading means uses a one thing for different purposes.
 Function overloading means more than one function having the same name for
different purposes.

 In function overloading the function have the same name but


signature of the function are must be different.

The signature of functions are different in following ways:-

1) No Of Parameters :-
void add(int,int);
void add(int,int,int);
void add(int,int,int.int);
In above example all three functions have same name add but the number of parameters for
each functions are different.

2) By Type of Parameters: -
void add(int,int);
void add(float,float);
void add(int,float);
In above example numbers of parameters are same but the type of parameter of the functions are
different.

3) By Sequence of parameters: -
Void add(int,
float); Void
add(float,int);

In above example the number of parameters and also the types of parameters are same
but the sequence of parameter is different.

Thus by using these three ways compiler differentiates the functions.


In short more than one function has the same name having different signature and purpose is
called as function overloading.

Example:-

1)

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

2)

#include<iostream>

using namespace std;

}
void add(int a, double b)

cout<<"sum = "<<(a+b);

void add(double a, int b)

cout<<endl<<"sum = "<<(a+b);

// Driver code

int main()

add(10,2.5);

add(5.5,6);

return 0;
Output
sum = 12.5
sum = 11.5

1] Run-Time Polymorphism / Dynamic Binding-


The second type of polymorphism is runtime polymorphism in which compiler decides
which function to call at run time so it is called as run time polymorphism. It is also called as
dynamic or late binding.

Run time polymorphism is implemented by using virtual function

.
Unit 4.Virtual function
Virtual function-
Virtual function allows programmer to declare a function in base class and define that
function name in both base and derived classes then function in the base class is declared as
virtual,
Syntax-
class <class_name>
{
public:
virtual <return_type><function_name>(arg s)

{
;

;
}
};
 Virtual function is define starting with keyword virtual.
 Virtual function is accessed through a pointer to the base class, the compiler decides
which function to be use at runtime using base class pointer.
class Base
{
public:
virtual void show()
{
cout<<"Base class";
}
};
class Derv1 : public Base
{
public:
void show()
{
cout<<"Derived class 1";
}
};
class Derv2 : public Base
{
public:
void show()
{
cout<<"Derived class 2";
}
};
void main()
{
Base *bptr;
Base B1;
Derv1 D1;
Derv2 D2;
bptr = &B1;
bptr --> show();
bptr = &D1;
bptr --> show();
bptr = &D2;
bptr--> show();
getch();
}
 In above example we create the derived classes derv1 and derv2 and a pointer in Base
class.
 Then we put address of a derived class object in the Base class pointer as,
Bpt = &derv1;
Bpt = &derv2;

 Then the member functions of the derived classes are executed at the statement Bptr 
show( ) executes different functions depending on the contain of pointer Bpt.
 So the compiler selects which function to call depending on the content of base pointed
and not on the type of pointer. This is done at runtime.

2)Example:

1. #include <iostream>
2. {
3. Class A
4. public:
5. virtual void display()
6. {
7. cout << "Base class is invoked"<<endl;
8. }
9. };
10. class B:public A
11. {
12. public:
13. void display()
14. {
15. cout << "Derived Class is invoked"<<endl;
16. }
17. };
18. int main()
19. {
20. A* a; //pointer of base class
21. B b; //object of derived class
22. a = &b;
23. a->display(); //Late Binding occurs
24. }

Output:

Derived Class is invoked


Rules for virtual function-

 The virtual function must be member of some class.


 They can not be a static member.
 They are accessed by using object pointer.
 The virtual function can not be a friend of another class.
 A virtual function must be define in base class.
 The prototype of virtual function in the base class is must be same in the derived class.
 We cannot have virtual constructor but we can have virtual destructor.

Pure Virtual function


o A virtual function is not used for performing any task. It only serves as a
placeholder.
o When the function has no definition, such function is known as "do-nothing"
function.
o The "do-nothing" function is known as a pure virtual function. A pure virtual
function is a function declared in the base class that has no definition relative to
the base class.
o A class containing the pure virtual function cannot be used to declare the objects of
its own, such classes are known as abstract base classes.
o The main objective of the base class is to provide the traits to the derived classes
and to create the base pointer used for achieving the runtime polymorphism.

Pure virtual function can be defined as:

1. virtual void display() = 0;

Let's see a simple example:

1. #include <iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. virtual void show() = 0;
7. };
8. class Derived : public Base
9. {
10. public:
11. void show()
12. {
13. std::cout << "Derived class is derived from the base class." << std::endl;
14. }
15.};
16.int main()
17.{
18. Base *bptr;
19. //Base b;
20. Derived d;
21. bptr = &d;
22. bptr->show();
23. return 0;
24.}

Output:

Derived class is derived from the base class.

Abstract Classes-

 Abstract Class is a class which contains at least one Pure Virtual function in it.
 Abstract classes are used to provide an Interface for its sub classes.
 Classes inheriting an Abstract Class must provide definition to the pure virtual function,
otherwise they will also become abstract class.

Characteristics of Abstract Class

 Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can
be created.
 Abstract class can have normal functions and variables along with a pure virtual function.
 Abstract classes are mainly used for Upcasting, so that its derived classes can use its
interface.
 Classes inheriting an Abstract Class must implement all pure virtual functions, or else
they will become Abstract too.
Example:

//Abstract base class

class Base //Abstract Class

public:

// Pure Virtual Function

};

class Derived:public Base

public:

void show()
cout << "Implementation of Virtual Function in Derived
class\n";

};

int main()

// Base obj; Compile Time Error we can't create object of


abstract class

Base *b;

Derived d;

b = &d;

b->show();

}
Output:-
Implementation of Virtual Function in Derived class

Friend Function:
 A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class.

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

 Even though the prototypes for friend functions appear in the class definition, friends
are not member functions.
 A friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends.
 A friend function can access the private and protected data of a class. We declare a
friend function using the friend keyword inside the body of the class.
Declaration of friend function:

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

In the above declaration, the friend function is preceded by the keyword friend.
The function can be defined anywhere in the program like a normal C++ function.
The function definition does not use either the keyword friend or scope
resolution operator.

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.

Let's see a 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.

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.

This Pointer:
In C++ programming, this is a keyword that refers to the current instance of the
class. There can be 3 main usage of this keyword in C++.

o It can be used to pass current object as a parameter to another method.


o It can be used to refer current class instance variable.
o It can be used to declare indexers.

Example:

Let's see the example of this keyword in C++ that refers to the fields of current
class.

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. Employee(int id, string name, float salary)
9. {
10. this->id = id;
11. this->name = name;
12. this->salary = salary;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18.};
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employe
e
21. Employee e2=Employee(102, "Nakul", 59000); //creating an object
of Employee
22. e1.display();
23. e2.display();
24. return 0;
25. }

Output:

101 Sonoo 890000


102 Nakul 59000

Virtual Destructor:
Deleting a derived class object using a pointer of base class type that has a
non-virtual destructor results in undefined behavior. To correct this
situation, the base class should be defined with a virtual destructor.
For example, the following program results in undefined behavior.

// CPP program without virtual destructor

// causing undefined behavior

#include <iostream>

using namespace std;

class base {

public:

base()

{ cout << "Constructing base\n"; }

~base()
{ cout<< "Destructing base\n"; }

};

class derived: public base {

public:

derived()

{ cout << "Constructing derived\n"; }

~derived()

{ cout << "Destructing derived\n"; }

};

int main()

derived *d = new derived();

base *b = d;

delete b;

getchar();

return 0;

Output
Constructing base
Constructing derived
Destructing base
Making base class destructor virtual guarantees that the object of derived
class is destructed properly, i.e., both base class and derived class
destructors are called. For example,

// A program with virtual destructor

#include <iostream>
using namespace std;

class base {

public:

base()

{ cout << "Constructing base\n"; }

virtual ~base()

{ cout << "Destructing base\n"; }

};

class derived : public base {

public:

derived()

{ cout << "Constructing derived\n"; }

~derived()

{ cout << "Destructing derived\n"; }

};

int main()

derived *d = new derived();

base *b = d;

delete b;

getchar();

return 0;

Output
Constructing base
Constructing derived
Destructing derived
Destructing base

You might also like