0% found this document useful (0 votes)
6 views34 pages

Unit-III (CPP) notes

The document discusses inheritance in C++, explaining the concepts of base and derived classes, visibility modes (protected, public, private), and various types of inheritance including single, multiple, multilevel, hierarchical, and hybrid inheritance. It also covers pointers, including pointers to objects and the 'this' pointer, as well as virtual functions and pure virtual functions. Examples are provided to illustrate each concept and demonstrate their implementation in C++.

Uploaded by

sakibmirza7498
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)
6 views34 pages

Unit-III (CPP) notes

The document discusses inheritance in C++, explaining the concepts of base and derived classes, visibility modes (protected, public, private), and various types of inheritance including single, multiple, multilevel, hierarchical, and hybrid inheritance. It also covers pointers, including pointers to objects and the 'this' pointer, as well as virtual functions and pure virtual functions. Examples are provided to illustrate each concept and demonstrate their implementation in C++.

Uploaded by

sakibmirza7498
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/ 34

UNIT-III

INHERITANCE
The ability to access members of one class by another class called inheritance.
At least two classes are required for inheritance.
1. Base class (Old class / Super class): A class that provides members to another
class called base class.
2. Derived class (New class / sub class): A class that can access members of base
class called derived class.
Derived class can access only protected and public members of base class.
Syntax of derived class:
};
class derived_class: mode base_class
{
Members of derived class
Here-
: is used to connect derived class to the base class.

VISIBILITY MODE
The visibility mode specifies how the features of the base class will be inherited by the
derived class. There are three types of visibility modes for all inheritance types in C++:

Protected Visibility Mode:


In the protected visibility mode, all the members of the base class become protected members
of the derived class. These members are now only accessible by the derived class and its
member functions. These members can also be inherited and will be accessible to the
inherited subclasses. However, objects of the derived classes cannot access these members
outside the class.
#include <iostream.h>
using namespace std;

// base class
class Base_class

public:

int x;

Public Visibility Mode: The characteristics of the base class have the least privacy under the
Public Visibility mode. The derived class can access the Public and protected members of the
base class but not the private members if the visibility mode is set to Public.

Private Visibility Mode: The setting provides the most privacy for the base class attributes. If
the visibility mode is set to private, the derived class can secretly access the Public and
protected members of a base class.

Protected Visibility Mode: Between public and private visibility modes comes protected
visibility mode. The derived class can access the protected and public members of the base
class protectively when the visibility mode is protected.
When object of derived class is creates then all data members of base class will be creates
then data members of derived class. Member functions of derived class can access only
protected and public members of base class.

TYPES OF INHERITANCE

These five types are as follows:

Single Inheritance
Single Inheritance is the most primitive among all the types of inheritance in C++. In this
inheritance, a single class inherits the properties of a base class. All the data members of the
base class are accessed by the derived class according to the visibility mode (i.e., private,
protected, and public) that is specified during the inheritance.

Single_Inheritance.

Syntax
class base_class_1

// class definition

};

class derived_class: visibility_mode base_class_1

// class definition

};

Description
A single derived_class inherits a single base_class. The visibility_mode is specified while
declaring the derived class to specify the control of base class members within the derived
class.

Example
The following example illustrates Single Inheritance in C++:

#include <iostream.h>

using namespace std;

// base class
class electronicDevice

public:

// constructor of the base class

electronicDevice()

cout << "I am an electronic device.\n\n";

};

// derived class

class Computer: public electronicDevice

public:

// constructor of the derived class

Computer()
{

cout << "I am a computer.\n\n";

};

int main()

// create object of the derived class

Computer obj; // constructor of base class and

// derived class will be called

return 0;

In the above example, the subclass Computer inherits the base class electronicDevice in a
public mode. So, all the public and protected member functions and data members of the
class electronicDevice are directly accessible to the class Computer. Since there is a single
derived class inheriting a single base class, this is Single Inheritance.

Multiple Inheritance
The inheritance in which a class can inherit or derive the characteristics of multiple classes,
or a derived class can have over one base class, is known as Multiple Inheritance. It specifies
access specifiers separately for all the base classes at the time of inheritance. The derived
class can derive the joint features of all these classes and the data members of all the base
classes are accessed by the derived or child class according to the access specifiers.

Syntax
class base_class_1

// class definition

};

class base_class_2

// class definition

};

class derived_class: visibility_mode_1 base_class_1, visibility_mode_2 base_class_2

// class definition

};
Description
The derived_class inherits the characteristics of two base classes, base_class_1 and
base_class_2. The visibility_mode is specified for each base class while declaring a derived
class. These modes can be different for every base class.

Example
#include<iostream.h>
class base1
{
protected:
int b1;
};
class base2
{
protected:
int b2;
};
class derived: public base1, public base2
{
int d;
public:
void getdata(int p1, int p2, int p3)
{
b1=p1;
b2=p2;
d=p3;
}
void shodata()
{
cout<<"\n data b1 is of base1 "<<b1;
cout<<"\n data b2 is of base2 "<<b2;
cout<<"\n data d is of derived "<<d;
}
};
void main()
{
derived od;
od.getdata(10,20,30);
od.showdata();
}
Output:
data g is of base1 10
data p is of base2 20
data c is of derived 30

Multilevel Inheritance
The inheritance in which a class can be derived from another derived class is known as
Multilevel Inheritance. Suppose there are three classes A, B, and C. A is the base class that
derives from class B. So, B is the derived class of A. Now, C is the class that is derived from
class B. This makes class B, the base class for class C but is the derived class of class A. This
scenario is known as the Multilevel Inheritance. The data members of each respective base
class are accessed by their respective derived classes according to the specified visibility
modes.

Syntax
class class_A

// class definition
};

class class_B: visibility_mode class_A

// class definition

};

class class_C: visibility_mode class_B

// class definition

};

Description
The class_A is inherited by the sub-class class_B. The class_B is inherited by the subclass
class_C. A subclass inherits a single class in each succeeding level.

Example
#include<iostream.h>
class grand
{
protected:
int g;
};
class parent: public grand
{
protected:
int p;
};
class child: public parent
{
int c;
public:
void getdata(int p1, int p2, int p3)
{
g=p1;
p=p2;
c=p3;
}
void shodata()
{
cout<<"\n data g is of super base (grand) "<<g;
cout<<"\n data p is of intermediate base (parent) "<<p;
cout<<"\n data c is of derived (child) "<<c;
}
};
void main()
{
child od;
od.getdata(10,20,30);
od.showdata();
}
Output:
data g is of super base (grand) 10
data p is of intermediate base (parent) 20
data c is of derived (child) 30

Hierarchical Inheritance
The inheritance in which a single base class inherits multiple derived classes is known as the
Hierarchical Inheritance. This inheritance has a tree-like structure since every class acts as a
base class for one or more child classes. The visibility mode for each derived class is
specified separately during the inheritance and it accesses the data members accordingly.

Syntax
class class_A

// class definition

};

class class_B: visibility_mode class_A

// class definition

};

class class_C : visibility_mode class_A


{

// class definition

};

class class_D: visibility_mode class_B

// class definition

};

class classE: visibility_mode class_C

// class definition

};

Description
The subclasses class_B and class_C inherit the attributes of the base class class_A. Further,
these two subclasses are inherited by other subclasses class_D and class_E respectively.

Example
The following example illustrates Hierarchical Inheritance in C++:
Example:
#include<iostream.h>
class base
{
protected:
int b;
};
class derived1: public base
{
int d1;
public:
void getdata(int p1, int p2)
{
b=p1;
d1=p2
}
void shodata()
{

}
cout<<"\n data b is of base "<<b;
cout<<"\n data d1 is of derived1 "<<d1;
};
class derived2: public base
{
int d2;
public:
void getdata(int p1, int p2)
{
b=p1;
d2=p2
}
void showdata()
{
cout<<"\n data b is of base "<<b;
cout<<"\n data d2 is of derived2 "<<d2;
}
};
void main()
{
derived1 od1;
od1.getdata(10,20);
od1.showdata();
derived2 od2;
od2.getdata(5,7);
od2.showdata();
}
Output:
data b is of base 10
data d1 is of derived1 20
data b is of base 5
data d2 is of derived2 7

Hybrid Inheritance
Hybrid Inheritance, as the name suggests, is the combination of two or over two types of
inheritances. For example, the classes in a program are in such an arrangement that they show
both single inheritance and hierarchical inheritance at the same time. Such an arrangement is
known as the Hybrid Inheritance. This is arguably the most complex inheritance among all
the types of inheritance in C++. The data members of the base class will be accessed
according to the specified visibility mode.
Syntax
class class_A

// class definition

};

class class_B

// class definition

};

class class_C: visibility_mode class_A, visibility_mode class_B

// class definition

};

class classD: visibility_mode class_C


{

// class definition

};

class classE: visibility_mode class_C

// class definition

};

Description
The derived class class_C inherits two base classes that are, class_A and class_B. This is the
structure of Multiple Inheritance. And two subclasses class_D and class_E, further inherit
class_C. This is the structure of Hierarchical Inheritance. The overall structure of Hybrid
Inheritance includes more than one type of inheritance.
#include<iostream.h>
class grand
{
protected:
int g;
};
class parent1: virtual public grand
{
protected:
int p1;
};
class parent2: virtual public grand
{
protected:
int p2;
};
{
private:
int c;
void getdata(int w, int x, int y, int z)
{
g=w;
p1=x;
p2=y;
c=z;
}
void showdata()
{
cout<<"\ngrand data is "<<g;
cout<<"\nparent1 data is "<<p2;
cout<<"\nparent2 data is "<<p1;
cout<<"\nchild data is "<<c;
}
};
void main()
{
child od;
od.getdata(10,20,30,40);
od.showdata();
}
Output:
grand data is 10
parent1 data is 20
parent2 data is 30
child data is 40
Pointers
A pointer is a variable that stores the address of another variable. Pointers can be used with
any data type, including basic types (e.g., int, char), arrays, and even user-defined types like
classes and structures.

Create Pointer
A pointer can be declared in the same way as any other variable but with an asterisk symbol
(*) as shown:
data_type* name
Here, data_type is the type of data that the pointer is pointing to, and name is the name
assigned to the pointer. The * symbol is also called dereference operator.

Example:
int* ptr;
In the above statement, we create a pointer ptr that can store the address of an integer data. It
is pronounced as "Pointer to Integer" or "Integer Pointer"
Pointer to Object
Pointers to objects aim to make a pointer that can access the object, not the variables. Pointer
to object in C++ refers to accessing an object.

There are two approaches by which you can access an object. One is directly and the other is
by using a pointer to an object in C++.

A pointer to an object in C++ is used to store the address of an object. For creating a pointer
to an object in C++, we use the following syntax:
classname*pointertoobject;
For storing the address of an object into a pointer in c++, we use the following syntax:
Syntax
pointertoobject=&objectname;

The above syntax can be used to store the address in the pointer to the object. After storing
the address in the pointer to the object, the member function can be called using the pointer to
the object with the help of an arrow operator.

Example:
// Example using an object pointer.

#include <iostream.h>
using namespace std;

class My_Class {
int num;
public:
void set_number(int value) {num = value;}
void show_number();
};

void My_Class::show_number()
{
cout << num << "\n";
}

int main()
{
My_Class object, *p; // an object is declared and a pointer to it
object.set_number(1); // object is accessed directly
object.show_number();

p = &object; // the address of the object is assigned to p


p->show_number(); // object is accessed using the pointer

return 0;
}

Output:
1
1
This Pointer
In C++, 'this' pointers is a pointer to the current instance of a class. It is used to refer to the
object within its own member functions.

#include <iostream>
using namespace std;

// Class that uses this pointer


class A {
public:
int a;
A(int a) {

// Assigning a of this object to


// function argument a
this->a = a;
}
void display() {

// Accessing a of this object


cout << "Value: " << this->a;
}
};

int main() {

// Checking if this works for the object


A o(10);
o.display();

return 0;
}
Output
Value: 10

Pointer to Derived Classes


A pointer is a data type that stores the address of other data types. Pointers can
be used for base objects as well as objects of derived classes. A pointer to the
object of the derived class and a pointer to the object of the base class are type-
compatible (may be used in different ways).
The pointer of Base Class pointing different objects of the derived class
Example:

Virtual Functions
A virtual function (also known as virtual methods) is a member function that is
declared within a base class and is re-defined (overridden) by a derived class.
When you refer to a derived class object using a pointer or a reference to the
base class, you can call a virtual function for that object and execute the derived
class's version of the method.
 Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for the function call.
 They are mainly used to achieve Runtime polymorphism.
 Functions are declared with a virtual keyword in a base class.
 The resolving of a function call is done at runtime.
Syntax
We can create a virtual function inside class using virtual keyword:

class Base{
public:
virtual return_type
functionName(){
// Function body
}
}

class Derived : public Base{


public:

// Overriden virtual
// function of the base
// class
return_type functionName(){
// Function body
}
}
Example:
#include <iostream>
using namespace std;

class Base {
public:

// Virtual function
virtual void display() {
cout << "Base class display" << endl;
}
};

class Derived : public Base {


public:

// Overriding the virtual


// function in the derived class
void display() {
cout << "Derived class display" << endl;
}
};
int main() {
Base* basePtr;
Derived derivedObj;

// Base class pointer pointing


// to derived class object
basePtr = &derivedObj;

// Calling the virtual function


basePtr->display();
return 0;
}
Output
Derived class display

Pure Virtual Function


A virtual function is called a pure virtual function if it does not have any
implementation and is assigned = 0. A class that contains a pure virtual
function is called an abstract class.
Example:
#include <iostream>
using namespace std;

class Base {
public:
// Pure virtual function
virtual void display() = 0;
};

class Derived : public Base {


public:

void display() override {


cout << "Derived class display" << endl;
}
};

int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;
basePtr->display();
return 0;
}
Output
Derived class display

Operator Overloading
In C++, Operator overloading is a compile-time polymorphism.
It is an idea of giving special meaning to an existing operator in
C++ without changing its original meaning.
C++ has the ability to provide the operators with a special
meaning for a data type, this ability is known as operator
overloading. Operator overloading is a compile-time
polymorphism. 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 Numbers, Fractional Numbers, Big
integers, etc.
Operator Function/Function Overloading
The definition of the function must differ from each other by
the types and/or the number of arguments in the argument list.
User cannot overload function declarations that differ only by
return type i.e. multiple definitions for the same function name
in the same scope.
Example:
#include <iostream.h>
using namespace std;

class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

int main(void) {
printData pd;

// Call print to print integer


pd.print(5);

// Call print to print float


pd.print(500.263);

// Call print to print character


pd.print("Hello C++");

return 0;
}
Output:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
Operator Overloading
Overloaded operators are functions with special names: the
keyword "operator" followed by the symbol for the operator
being defined. Like any other function, an overloaded operator
has a return type and a parameter list. It involve two kinds of
Operator overloading and they are:

Unary Operator Overloading


The unary operators operate on a single operand and following are the examples
of Unary operators −
 The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator.
Example:
#include <iostream.h>
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;
}
Output:
F: -11 I:-10
F: 5 I:-11

Binary Operator overloading


Operator overloading is a compile polymorphic technique where a single
operator can perform multiple functionalities.It is especially for operations
involving two operands.As a result, the operator that is overloaded is capable to
provide special meaning to the user-defined data types as well. We can overload
binary operators like +,*/, – etc to directly manipulate the object of a class.
Syntax:

return_type::operator binary_operator_symbol(parameters){
// function definition
}
Example:
/ Write a program to demonstrate binary operator overloading
#include <iostream>
using namespace std;
class complex
{
int a, b;
public:

void get_data(){
cout << "Enter the value of Complex Numbers a, b: "; cin >> a >> b;
}
complex operator+(complex ob)// overaloded operator function +
{
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
}

complex operator-(complex ob)// overaloded operator function -


{
complex t;
t.a = a - ob.a;
t.b = b - ob.b;
return (t);
}

void display(){
cout << a << "+" << b << "i" << "\n";
}
};

int main()
{
complex obj1, obj2, result, result1;
obj1.get_data();
obj2.get_data();
result = obj1 + obj2;
result1 = obj1 - obj2;

cout << "\n\nInput Values:\n";

obj1.display();
obj2.display();

cout << "\nResult:";

result.display();
result1.display();

return 0;
}
Output
Enter the value of Complex Numbers a, b: 7 5
Enter the value of Complex Numbers a, b: 3 4

Input Values:
7+5i
3+4i

You might also like