Unit 3 205
Unit 3 205
A class is a user-defined data type, which contain data members and member functions, which can be
accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.
When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created)
memory is allocated.
class ClassName {
access_specifier:
// Body of the class
};
ClassName ObjectName;
MyClass obj;
if the name of the object is obj and you want to access the member function with the
name printName() then you will have to write:
obj.printName();
// object
#include <iostream>
#include <string>
class Person {
public:
// Data members
string name;
int age;
void introduce()
cout << "Hi, my name is " << name << " and I am "
};
int main()
Person person1;
person1.name = "Alice";
person1.age = 30;
person1.introduce();
return 0;
Output
Hi, my name is Alice and I am 30 years old.
Access Modifiers
there are 3 access specifiers that are as follows:
1. Public: Members declared as public can be accessed from outside the class.
2. Private: Members declared as private can only be accessed within the class itself.
3. Protected: Members declared as protected can be accessed within the class and by derived
classes.
If we do not specify the access specifier, the private specifier is applied to every member by default.
Scope Resolution
The scope resolution operator is used to reference the global variable or member function that is out
of scope. Therefore, we use the scope resolution operator to access the hidden variable or function of
a program. The operator is represented as the double colon (::) symbol.
2. It defines the member function outside of the class using the scope resolution.
//Program to define the member function outside of the class using the scope resolution
(::) operator
1. #include <iostream>
2. using namespace std;
3. class Operate
4. {
5. public:
6. // declaration of the member function
7. void fun();
8. };
9. // define the member function outside the class.
10. void Operate::fun() /* return_type Class_Name::function_name */
11. {
12. cout << " It is the member function of the class. ";
13. }
14. int main ()
15. {
16. // create an object of the class Operate
17. Operate op;
18. op.fun();
19. return 0;
20. }
Output
Syntax:
ClassName()
{
//Constructor's Body
}
Destructors
Like a constructor, Destructor is also a member function of a class that has the
same name as the class name preceded by a tilde(~) operator. It helps to deallocate
the memory of an object. It is called while the object of the class is freed or
deleted. In a class, there is always a single destructor without any parameters so it
can’t be overloaded. It is always called in the reverse order of the constructor. if a
class is inherited by another class and both the classes have a destructor then the
destructor of the child class is called first, followed by the destructor of the parent
or base class.
~ClassName()
{
//Destructor's Body
}
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. }
A friend class can access private and protected members of other classes in which it is declared as a
friend.
#include <iostream>
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
private_variable = 10;
protected_variable = 99;
friend class F;
};
#include <iostream>
class A
public:
int x;
cout<<"Hello World!" ;
}
x=a;
x = i.x;
};
int main()
{
A a;
cout<<a2.x;
return 0;
}
output
Hello world
20
For accessing the data, the declaration of a friend function should be done inside the body of a class
starting with the keyword friend.
1. class class_name
2. {
4. };
o It cannot be called using the object as it is not in the scope of that class.
#include <iostream>
class A
int x;
public:
void setdata(int i)
x=i;
};
class B
int y;
public:
void setdata(int i)
y=i;
};
void min(A a,B b)
if(a.x<=b.y)
else
int main()
A a;
B b;
a.setdata(10);
b.setdata(20);
min(a,b);
return 0;
Inheritance
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.
Where,
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.
class Account {
public:
};
public:
};
int main() {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
C++ Polymorphism
Polymorphism is an important concept of object-oriented programming. It simply means more than one
form. That is, the same entity (function or operator) behaves differently in different scenarios.
int a = 5;
int b = 6;
int sum = a + b; // sum = 11
And when we use the + operator with strings, it performs string concatenation. For example,
In C++, we can use two functions having the same name if they have different parameters (either types
or number of arguments).
And, depending upon the number/type of arguments, different functions are called. For example,
// C++ program to overload sum() function
#include <iostream>
int main() {
return 0;
}
Sum 1 = 11
Sum 2 = 12.1
Sum 3 = 18
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.
o Sizeof
o member selector(.)
o ternary operator(?:)
2. {
4. }
Where the return type is the type of value returned by the function.
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.
1. #include <iostream>
3. class Test
4. {
5. private:
6. int num;
7. public:
8. Test(): num(8){}
10. {
12. }
15. }
16. };
18. {
21. tt.Print();
22. return 0;
23. }
Single Inheritance-
class parent_class
};
};
Syntax Description
visibility_mode: Type of the visibility mode (i.e., private, protected, and public) that specifies
how the data members of the child class inherit from the parent class.
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.
Syntax
class base_class_1
// class definition
};
class base_class_2
// class definition
};
// 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.
#include <iostream>
// class_A
class electronicDevice
public:
electronicDevice()
};
// class_B
class Computer
public:
Computer()
};
{};
int main()
{
// create object of the derived class
// will be called
return 0;
Multilevel Inheritance
The inheritance in which a class can be derived from another derived class is known as
Multilevel Inheritance.
Syntax
class class_A
{
// class definition
};
// class definition
};
// 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.
By Ravikiran A S
During inheritance, the data members of the base class get copied in the derived class and can
be accessed depending upon the visibility mode used. The order of the accessibility is always in
a decreasing order i.e., from public to protected. There are mainly five types of Inheritance
in C++ that you will explore in this article. They are as follows:
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Inheritance is a method through which one class inherits the properties from its parent class.
Inheritance is a feature in which one new class is derived from the existing ones. The new class
derived is termed a derived class, and the current class is termed a Parent or base class.
Inheritance is one of the most essential features of Object Oriented Programming. Rather than
defining new data functions while creating a class, you can inherit the existing class's data
functions. The derived class takes over all the properties of the parent class and adds some new
features to itself. For example, using inheritance, you can add the members' names and
descriptions to a new class.
To clearly understand the concept of Inheritance, you must learn about two terms on which the
whole concept of inheritance is based - Child class and Parent class.
Child class: The class that inherits the characteristics of another class is known as the child class
or derived class. The number of child classes that can be inherited from a single parent class is
based upon the type of inheritance. A child class will access the data members of the parent
class according to the visibility mode specified during the declaration of the child class.
Parent class: The class from which the child class inherits its properties is called the parent class
or base class. A single parent class can derive multiple child classes (Hierarchical Inheritance) or
multiple parent classes can inherit a single base class (Multiple Inheritance). This depends on the
different types of inheritance in C++.
The syntax for defining the child class and parent class in all inheritance types in C++ is given
below:
class parent_class
};
};
Syntax Description
visibility_mode: Type of the visibility mode (i.e., private, protected, and public) that specifies
how the data members of the child class inherit from the parent class.
Instead of trying to replicate what already exists, it is always ideal to reuse it since it saves time
and enhances reliability. In C++, inheritance is used to reuse code from existing classes. C++
highly supports the principle of reusability. Inheritance is used when two classes in a program
share the same domain, and the properties of the class and its superclass should remain the
same. Inheritance is a technique used in C++ to reuse code from pre-existing classes. C++
actively supports the concept of reusability.
To create a parent class that is derived from the base class below is a syntax that you should
follow:
class
<derived_class_name> : <access-specifier>
<base_class_name>
/ /body
Here, class is a keyword which is used to create a new class, derived_class_name is the new
class name which will inherit the properties of a base class, and access-specifier defines through
mode the derived class has been created, whether through public, private or protected mode
and the base_class_name is the name of the base class.
Public Inheritance: The public members of the base class remain public even in the derived class;
the same applies to the protected members.
Private Inheritance: This makes public members and protected members from the base class to
be protected in the derived class. The derived class has no access to the base class's private
members.
Protected Inheritance protects the Public and protected members from the derived class's base
class.
Inheritance makes the programming more efficient and is used because of the benefits it
provides. The most important usages of inheritance are discussed below:
1. Code reusability: One of the main reasons to use inheritance is that you can reuse the code. For
example, consider a group of animals as separate classes - Tiger, Lion, and Panther. For these
classes, you can create member functions like the predator() as they all are predators, canine()
as they all have canine teeth to hunt, and claws() as all the three animals have big and sharp
claws. Now, since all the three functions are the same for these classes, making separate
functions for all of them will cause data redundancy and can increase the chances of error. So
instead of this, you can use inheritance here. You can create a base class named carnivores and
add these functions to it and inherit these functions to the tiger, lion, and panther classes.
2. Transitive nature: Inheritance is also used because of its transitive nature. For example, you
have a derived class mammal that inherits its properties from the base class animal. Now,
because of the transitive nature of the inheritance, all the child classes of ‘mammal’ will inherit
the properties of the class ‘animal’ as well. This helps in debugging to a great extent. You can
remove the bugs from your base class and all the inherited classes will automatically get
debugged.
Visibility Modes
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++:
In the public visibility mode, it retains the accessibility of all the members of the base class. The
members specified as public, protected, and private in the base class remain public, protected,
and private respectively in the derived class as well. So, the public members are accessible by
the derived class and all other classes. The protected members are accessible only inside the
derived class and its members. However, the private members are not accessible to the derived
class.
The following code snippet illustrates how to apply the public visibility mode in a derived class:
class base_class_1
// class definition
};
// class definition
};
The following code displays the working of public visibility mode with all three access specifiers
of the base class:
class base_class
private:
//class member
int base_private;
protected:
//class member
int base_protected;
public:
//class member
int base_public;
};
private:
int derived_private;
// int base_private;
protected:
int derived_protected;
// int base_protected;
public:
int derived_public;
// int base_public;
};
int main()
derived_class obj;
obj.base_public; // Accessible
In the above example, the derived class inherits the base class as public. The private members
are not accessible at all by the derived class. The protected members are only accessible inside
the derived class and not accessible outside the class. And the public members are accessible
inside and outside the class.
In the private visibility mode, all the members of the base class become private in the derived
class. This restricts the access of these members outside the derived class. They can only be
accessed by the member functions of the derived class. And in this case, the derived class does
not inherit the private members.
The following code snippet illustrates how to apply the private visibility mode in a derived class:
class base_class_1
{
// class definition
};
// class definition
};
The following code displays the working of private visibility mode with all three access specifiers
of the base class:
class base_class
private:
//class member
int base_private;
protected:
//class member
int base_protected;
public:
//class member
int base_public;
};
private:
int derived_private;
// int base_private;
// int base_protected;
// int base_public
protected:
int derived_protected;
public:
int derived_public;
};
int main()
derived_class obj;
}
In the above example, the derived class inherits the base class privately. So, all the members of
the base class have become private in the derived class. The error is thrown when the object of
the derived class tries to access these members outside the class.
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.
The following code snippet illustrates how to apply the protected visibility mode in a derived
class:
class base_class_1
// class definition
};
// class definition
};
The following code displays the working of protected visibility mode with all three access
specifiers of the base class:
class base_class
private:
//class member
int base_private;
protected:
//class member
int base_protected;
public:
//class member
int base_public;
};
private:
int derived_private;
// int base_private;
protected:
int derived_protected;
// int base_protected;
// int base_public
public:
int derived_public;
};
int main()
derived_class obj;
In the above example, the derived class inherits the base class in protected mode. All the
members of the base class are now only accessible inside the derived class and not anywhere
outside the class. So it throws an error when the object obj of the derived class tries to access
these members outside the class.
The following table illustrates the control of the derived classes over the members of the base
class in different visibility modes:
Not Not
Not
Inherited Inherited
Inherited /
PRIVATE / /
Remains
Remains Remains
Private
Private Private
There are five inheritance types in C++ based upon how the derived class inherits its features
from the base class. 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.
Syntax
class base_class_1
// class definition
};
class derived_class: visibility_mode base_class_1
// class definition
};
Description
Example
#include <iostream>
// base class
class electronicDevice
public:
electronicDevice()
};
// derived class
public:
// constructor of the derived class
Computer()
};
int main()
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 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>
// class_A
class electronicDevice
public:
electronicDevice()
};
// class_B
class Computer
public:
Computer()
}
};
{};
int main()
// will be called
return 0;
In the above example, there are separate base classes, electronicDevice, and Computer. The
derived class Linux_based inherits both of these classes forming a Multiple Inheritance
structure. The derived class Linux_based has inherited the attributes of both base classes in
public mode. When you create an object of the derived class, it calls the constructor of both the
base classes.
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 definition
};
// 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>
// class_A
class electronicDevice
public:
electronicDevice()
};
public:
Computer()
};
public:
Linux_based()
};
int main()
return 0;
}
Hierarchical Inheritance
yntax
class class_A
// class definition
};
// class definition
};
// class definition
};
// class definition
};
// 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
#include <iostream>
// base class
class electronicDevice
public:
electronicDevice()
};
{};
{};
int main()
return 0;
Hybrid Inheritance
Syntax
class class_A
// class definition
};
class class_B
{
// class definition
};
// class definition
};
// class definition
};
// class definition
};
#include <iostream>
// base class 1
class electronicDevice
public:
};
// base class 2
class Computer
public:
Computer()
};
{};
{};
int
main()
return 0;
o A C++ virtual function is a member function in the base class that you redefine in a derived
class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.
1. #include <iostream>
3. class A
4. {
5. int x=5;
6. public:
7. void display()
8. {
10. }
11. };
13. {
14. int y = 10;
15. public:
17. {
19. }
20. };
22. {
23. A *a;
24. B b;
25. a = &b;
26. a->display();
27. return 0;
28. }
Value of x is : 5
Program to be prepared