0% found this document useful (0 votes)
7 views55 pages

C++ Unit 4

The document provides an overview of operator overloading and inheritance in C++. It explains how operators can be overloaded for user-defined classes, including syntax and rules, as well as different types of inheritance such as single, multilevel, multiple, hierarchical, and hybrid inheritance. Additionally, it discusses the concept of virtual base classes to resolve ambiguity in multiple inheritance scenarios.

Uploaded by

nithyaselvam394
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views55 pages

C++ Unit 4

The document provides an overview of operator overloading and inheritance in C++. It explains how operators can be overloaded for user-defined classes, including syntax and rules, as well as different types of inheritance such as single, multilevel, multiple, hierarchical, and hybrid inheritance. Additionally, it discusses the concept of virtual base classes to resolve ambiguity in multiple inheritance scenarios.

Uploaded by

nithyaselvam394
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Operator Overloading

 In C++, we can make operators to work for user defined classes.

 This means C++ has the ability to provide the operators with a
special meaning for a data type, this ability is known as operator
overloading.

 For example, we can overload an operator ‘+’ in a class like


String so that we can concatenate two strings by just using +.

 Other example classes where arithmetic operators may be


overloaded are Complex Number, Fractional Number, Big
Integer, etc.
Syntax of Operator Overloading
 return_type class_name : : operator op(argument_list)
{
// body of the function.
}

 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.
Implementing of Operator overloading:

1. Member function: It is in the scope of the class in which it is


declared.

2. Friend function: It is a non-member function of a class with


permission to access both private and protected members.

3. Non-Member Function: the scope of this function is within


the program.
Rules for Operator Overloading
 Existing operators can only be overloaded, but the new
operators cannot be overloaded.

 The overloaded operator contains atleast one operand of the


user-defined data type.

 We cannot use friend function to overload certain operators.

 However, the member function can be used to overload those


operators.

 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.
 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.

Operator that cannot be overloaded are as follows:

 Scope operator (::)


 Sizeof
 member selector(.)
 member pointer selector(*)
 ternary operator(?:)
Overloading special operators:
 Some of the special operators in C++ are as follows:
 new – It is used to allocate the memory dynamically.
 Delete – It is used to free the memory dynamically.
 [] – It is a subscript operator.
 -> – – It is a member access operators.
 = – It is used to assign the values.
 () – It is used for function call.
What is the difference between operator functions and
normal functions?

 Operator functions are the same as normal functions.


 The only differences are, name of an operator function is
always operator keyword followed by symbol of operator
and operator functions are called when the corresponding
operator is used.
Example
#include <iostream>
class Test
{ Output:
public:
int num = 8; The count is : 10
void operator ++()
{
num = num+2;
}
void Print()
{
cout<<"The Count is: "<<num;
}
};

int main()
{
Test tt;
++tt; // calling of a function "void operator
++()"
tt.Print();
return 0;
}
Operator Overloading in Unary Operators
 In unary operator function, no arguments should be
passed.
 It works only with one class objects. It is a overloading
of an operator operating on a single operand.
 The Unary minus ( – ) operator, Logical not ( ! )
operator,
 Increment operator ++ and decrement operator -- are
examples of unary operators.
 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.
Syntax:
return_type :: operator binary_operator_symbol ()
{
// function definition
}
Example:
#include<iostream.h>
#include<conio.h>
class unary
{
int a;
float b;
public:
void getdata()
{
cout<<"\n enter an integer value:";
cin>>a;
cout<<"\nenter the float value:";
cin>>b;
}
void putdata()
{
cout<<"a="<<a<<"\t"<<"b="<<b<<endl;
}
void operator++()
{
++a;
++b;
}
void operator--()
{
--a;
--b;
}
void operator-()
{
a=-a;
b=-b;
}
};
int main()
{
clrscr();
cout<<"\n\t\tUNARY OPERATOR OVERLOADING";
unary u;
u.getdata();
cout<<"\npre-decreament operator overloading\n";
--u;
u.putdata();
cout<<"unary minus operator overloading\n";
-u;
u.putdata();
cout<<"pre-increament operator overloading\n";
++u;
u.putdata();
getch();
return 0;
}
Output
Overloading Binary Operator
 Binary operators work on two operands.

 In binary operator overloading function, there should be


one argument to be passed.

 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.

 There are multiple binary operators like +, -, *, /, etc., that


can directly manipulate or overload the object of a class.
Syntax:
return_type :: operator binary_operator_symbol (arg)
{
// function definition
}

Example:
#include<iostream.h>
#include<conio.h>
class complex
{
float x,y;
public:
void getdata()
{
cout<<"\n enter the 2 float values:";
cin>>x>>y;
}
void putdata()
{
if(y>0)
cout<<x<<"+j"<<y<<endl;
else
{
y=-y;
cout<<x<<"-j"<<y<<endl;
}
}
complex operator+(complex);
friend complex operator-(complex,complex);
};
complex complex::operator+(complex c)
{
complex t;
t.x=x+c.x;
t.y=y+c.y;
return t;
}
complex operator-(complex t1,complex t2)
{
complex t3;
t3.x=t1.x-t2.x;
t3.y=t1.y-t2.y;
return t3;
}
int main()
{
clrscr();
cout<<"\t\tBINARY OPERATOR OVERLOADING";
complex c1,c2,c3;
c1.getdata();
c2.getdata();
c3=c1+c2;
cout<<"addition of 2 complex numbers\n";
c3.putdata();
c3=c1-c2;
cout<<"subtraction of 2 complex numbers\n";
c3.putdata();
getch();
return 0;
}
OUTPUT:
Inheritance
 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.

 The capability of a class to derive properties and


characteristics from another class is called Inheritance

 Sub Class/ Derived Class / Child Class: The class that


inherits properties from another class is called Sub class or
Derived Class.
 Super Class / Base Class / Parent Class: The class whose
properties are inherited by sub class is called Base Class or
Super class.
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.

Derived Classes
 A Derived class is defined as the class derived from the base
class.
The Syntax of Derived class:
class derived_class_name : visibility-mode base_class_name
{
// body of the derived class.
}
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.

Modes of Inheritance
 Public mode: If we derive a sub class from a public base
class. Then the public member of the base class will
become public in the derived class and protected members
of the base class will become protected in derived class.

 Protected mode: If we derive a sub class from a Protected


base class. Then both public member and protected
members of the base class will become protected in
derived class.
Private mode: If we derive a sub class from a Private base class.
Then both public member and protected members of the base
class will become Private in derived class.
Note:
In C++, the default mode of visibility is private.
The private members of the base class are never inherited.

Example for visibility mode in inheritance


class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};
Types of Inheritance
Single Inheritance: In single inheritance, one sub class is
allowed to
inherit from only one base class.

Example:

#include <iostream>

// base class
class Animal
{

public:
void eat()
{
cout << "I can eat!" << endl;
}
void sleep()
{
cout << "I can sleep!" << endl;
}
};

// derived class
class Dog : public Animal
{

public:
void bark()
{
cout << "I can bark" << endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;

// Calling members of the base class


dog1.eat();
dog1.sleep();

// Calling member of the derived class


dog1.bark();

return 0;
}
Output:

I can eat!
I can sleep!
I can bark
Multilevel Inheritance
 In this type of inheritance, a derived class is created
from another derived class.
 Inheritance is transitive so the last derived class
acquires all the members of all its base classes.
Example:
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}

Output:
Eating…
Barking…
Weeping…
Multiple Inheritance
 Multiple inheritance is the process of deriving a new
class that inherits the attributes from two or more
classes.
 i.e one sub class is inherited from more than one base
classes.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2,
....
{
// body of subclass
};
Example:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};
class B

protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10); Output:
c.get_b(20); The value of a is : 10
c.display(); The value of b is : 20
return 0; Addition of a and b is : 30
}
Hierarchical Inheritance
 Hierarchical inheritance is defined as the process of
deriving more than one class from only one base class.
Example:

#include<iostream>
using namespace std;

// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
// first sub class
class Car: public Vehicle
{

};

// second sub class


class Bus: public Vehicle
{

};
Output
// main function
int main() This is a Vehicle
{ This is a Vehicle
Car obj1;
Bus obj2;
return 0;
}
Hybrid Inheritance
 Hybrid (Virtual) Inheritance: Hybrid Inheritance
is implemented by combining more than one type of
inheritance.
 For example: Combining Hierarchical inheritance
and Multiple Inheritance.
 Below image shows the combination of hierarchical
and multiple inheritance:
Example: ( Practical Program)

#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rollnum;
public:
void getnum()
{
cout<<"\nenter the roll number:";
cin>>rollnum;
}
void putnum()
{
cout<<"\n roll no:"<<rollnum;
}
};
class test:public student
{
protected:
float mark1,mark2;
public:
void getmarks()
{
cout<<"\nenter mark1(<=50):";
cin>>mark1;
cout<<"\nenter mark2(<=50):";
cin>>mark2;
}
void putmarks()
{
cout<<"\n mark1:"<<mark1;
cout<<"\n mark2:"<<mark2;
}
};
class sports
{
protected:
float score;
public:
if(total<50)
cout<<"\nthe student is fail";
else void getscore()
{
cout<<"\nenter the score(0-10):";
cin>>score;
}
void putscore()
{
cout<<"\nscore:"<<score;
}
};
class result:public test,public sports
{
float total;
public:
void display();
};
void result::display()
{
getnum();
getmarks();
getscore();
total=mark1+mark2+score;
putnum();
putmarks();
putscore();
cout<<"\ntotal:"<<total;

cout<<"\nthe student is pass";


}
int main()
{
clrscr();
cout<<"\n\tHYBRID INERITANCE\n";
result r;
r.display();
getch();
return 0;
}
Output:
Virtual Base Class
 Virtual base classes are used in virtual inheritance in a
way of preventing multiple “instances” of a given class
appearing in an inheritance hierarchy when using
multiple inheritances

Need for Virtual Base Classes:


 Consider the situation where we have one class A .This
class is A is inherited by two other classes B and C.
Both these class are inherited into another in a new
class D as shown in figure below
 As we can see from the figure that data
members/function of class A are inherited twice to class
D.

 One through class B and second through class C. When


any data / function member of class A is accessed by an
object of class D, ambiguity arises as to which
data/function member would be called? One inherited
through B or the other inherited through C.

 This confuses compiler and it displays error.


Example 1: To Show the need of Virtual Base Class:
#include <iostream>

class A
{
public:
void show()
{
cout << "Hello form A \n";
}
};

class B : public A
{

};

class C : public A
{

};
class D : public B, public C
{

};

int main()
{
D object;
object.show();
}
How to resolve this issue?
To resolve this ambiguity when class A is inherited in
both class B and class C, it is declared as virtual base
class by placing a keyword virtual as :
Syntax for Virtual Base Classes
Syntax 1:
class B : virtual public A
{
};

Syntax 2:
class C : public virtual A
{
};
Note:

 virtual can be written before or after the public. Now only


one copy of data/function member will be copied to class C.

 class B and class A becomes the virtual base class.


Example:
#include <iostream>

class A
{
public:
int a;
A() // constructor
{
a = 10;
}
};

class B : public virtual A


{
};
class C : public virtual A
{
};

class D : public B, public C


{
};

int main()
{
D obj;
cout << "a = " << obj.a << endl;

return 0;
}

Output:
a = 10

You might also like