BT205 BCE Unit 3
BT205 BCE Unit 3
Topic Covered
Object & Classes, Scope Resolution Operator, Constructors & Destructors, Friend
Functions, Inheritance, Polymorphism, Overloading Functions & Operators, Types of
Inheritance, Virtual functions. Introduction to Data Structures.
Objects
Objects are the basic run time entities in an object-oriented system. They may represent a person,
a place, a bank account, a table of data or any item that the program has to handle. They may
also represent user-defined data such as vectors, time and lists. Programming problem is
analyzed in term of objects and the nature of communication between them. Program objects
should be chosen such that they match closely with the real-world objects. Objects take up space
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
in the memory and have an associated address like a record in Pascal, or a structure in c. When a
program is executed, the objects interact by sending messages to one another. For example, if
“customer” and “account” are to object in a program, then the customer object may send a
message to the count object requesting for the bank balance. Each object contain data, and code
to manipulate data. Objects can interact without having to know details of each other’s data or
code. It is a sufficient to know the type of message accepted, and the type of response returned
by the objects. Although different author represent them differently fig 1.2 shows two notations
that are popularly used in object oriented analysis and design.
Classes
We just mentioned that objects contain data, and code to manipulate that data. The entire set of
data and code of an object can be made a user-defined data type with the help of class. In fact,
objects are variables of the type class. Once a class has been defined, we can create any number
of objects belonging to that class. Each object is associated with the data of type class with which
they are created. A class is thus a collection of objects similar types. For examples, Mango,
Apple and orange members of class fruit. Classes are user-defined that types and behave like the
built-in types of a programming language. The syntax used to create an object is not different
then the syntax used to create an integer object in C. If fruit has been defines as a class, then the
statement Fruit Mango; will create an object mango belonging to the class fruit.
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
Inheritance
Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification. For example, the bird,
‘robin’ is a part of class ‘flying bird’ which is again a part of the class ‘bird’. The principal
behind this sort of division is that each derived class shares common characteristics with the
class from which it is derived as illustrated in fig 1.3. In OOP, the concept of inheritance
provides the idea of reusability. This means that we can add additional features to an existing
class without modifying it. This is possible by deriving a new class from the existing one. The
new class will have the combined feature of both the classes. The real appeal and power of the
inheritance mechanism is that it
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
Allows the programmer to reuse a class i.e. almost, but not exactly, what he wants, and to tailor
the class in such a way that it does not introduced any undesirable side-effects into the rest of
classes.
Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than on form. An operation may exhibit different behavior is different
instances. The behavior depends upon the types of data used in the operation. For example,
consider the operation of addition. For two numbers, the operation will generate a sum. If the
operands are strings, then the operation would produce a third string by concatenation. The
process of making an operator to exhibit different behaviors in different instances is known as
operator overloading. Fig. 1.4 illustrates that a single function name can be used to handle
different number and different types of argument. This is something similar to a particular word
having several different meanings depending upon the context. Using a single function name to
perform different type of task is known as function overloading.
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
Polymorphism plays an important role in allowing objects having different internal structures to
share the same external interface. This means that a general class of operations may be accessed
in the same manner even though specific action associated with each operation may differ.
Polymorphism is extensively used in implementing inheritance.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means that the code associated with a given procedure call is not known until
the time of the call at run time. It is associated with polymorphism and inheritance. A function
call associated with a polymorphic reference depends on the dynamic type of that reference.
Consider the procedure “draw” in fig. 1.3. by inheritance, every object will have this procedure.
Its algorithm is, however, unique to each object and so the draw procedure will be redefined in
each class that defines the object. At run-time, the code matching the object under current
reference will be called.
Message Passing
An object-oriented program consists of a set of objects that communicate with each other. The
process of programming in an object-oriented language, involves the following basic steps:
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
Class:
A class is a user defined data type which binds data and its associated functions together. It
allows the data and functions to be hidden, if necessary from external use. Generally, a class
specification has two parts.
i) Class declaration: it describes the type & scope of its members.
ii) Class function definitions: It describes how the class functions are implemented.
Class declaration.
The general form of a class is
class class-name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
1) The class keyword specifies that what follows is an abstract data of type class name. The body
of a class is enclosed within braces & terminated by semicolon.
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
2) The class body consists of declaration of variables & functions which are called as members
& they are grouped under two sections i.e. private & public.
3) Private and public are known as visibility labels, where private can be accessed only from
within the class where public members can be accessed from outside the class also. By default,
members of a class are private.
4) The variable declared inside the class are known as data members & functions are known as
member functions. Only the member function can have access to the private data members &
private functions. However the public members can be accessed from outside the class.
Creating objects
Object is an instance or variable of the class. Once a class has been declared. We can create
variables of that type by using the class name.
Ex . item x;
Here class variables are known as object therefore, x is called an object of type item and
necessary memory space is allocated to an object.
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
OUTPUT
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
number : 100
cost : 20.3
We have already seen the class definition syntax as well as an example. In C++, the member
functions can be coded in two ways :
(a) Inside class definition
(b) Outside class definition using scope resolution operator (::) The code of the function is same
in both the cases, but the function header is different as explained below :
Class myclass
{
int a;
public:
void set_a(int num); //member function declaration
int get_a( ); //member function declaration
}; //member function definition outside class using scope resolution operator
void myclass :: set_a(intnum)
{
a=num;
}
int myclass::get_a( )
{
return a;
}
Another use of scope resolution operator is to allow access to the global version of a variable. In
many situation, it happens that the name of global variable and the name of the local variable are
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
same .In this while accessing the variable, the priority is given to the local variable by the
compiler. If we want to access or use the global variable, then the scope resolution operator (::) is
used.
Constructor:
A constructor is a special member function whose task is to initialize the objects of its class. It is
special because its name is same as the class name. The constructor is invoked whenever an
object of its associated class is created. It is called constructor because it construct the value data
members of the class.
The constructor functions have some special characteristics.
They should be declared in the public section.
They are invoked automatically when the objects are created.
They do not have return types, not even void and therefore, they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
These cannot be static.
Default and copy constructors are generated by the compiler wherever required.
Generated constructors are public.
These can have default arguments as other C++ functions.
Example:
#include< iostream>
Using namespace std;
class myclass
{ // class declaration
int a;
public:
myclass( ); //default constructor
void show( );
};
myclass :: myclass( )
{
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
Default constructor
The default constructor for any class is the constructor with no arguments. When no arguments
are passed, the constructor will assign the values specifically assigned in the body of the
constructor. It can be zero or any other value. The default constructor can be identified by the
name of the class followed by empty parentheses. Above program uses default constructor. If it
is not defined explicitly, then it is automatically defined implicitly by the system.
Parameterized Constructor
It is possible to pass arguments to constructors. Typically, these arguments help initialize an
object when it is created. To create a parameterized constructor, simply add parameters to it the
way you would to any other function. When you define the constructor's body, use the
parameters to initialize the object.
#include <iostream>
Using namespace std;
class myclass
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
{
int a, b;
public:
myclass (int i, int j) //parameterized constructor
{
a=i;
b=j;
}
void show()
{
cout << a << " " << b;
}
};
int main()
{
myclass ob(3, 5); //call to constructor
ob.show();
return 0;
}
C++ supports constructor overloading. A constructor is said to be overloaded when the same
constructor with different number of argument and types of arguments initializes an object.
Copy Constructors
The copy constructor is a constructor which creates an object by initializing it with an object of
the same class, which has been created previously. If class definition does not explicitly include
copy constructor, then the system automatically creates one by default. The copy constructor is
used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
The most common form of copy constructor is shown here:
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
DESTRUCTOR
A destructor destroys an object after it is no longer in use. The destructor, like constructor, is a
member function with the same name as the class name. But it will be preceded by the character
Tilde (~).
A destructor takes no arguments and has no return value.
Each class has exactly one destructor.
If class definition does not explicitly include destructor, then the system automatically creates
one by default. It will be invoked implicitly by the compiler upon exit from the program to clean
up storage that is no longer accessible.
// A Program showing working of constructor and destructor //
#include <iostream>
Using namespace std;
class Myclass
{
public:
int x;
Myclass() //Constructor
{
x=10;
}
~Myclass() //Destructor
{
cout<<“destructing…”;
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
}
int main (}
{
Myclass obj1, obj2;
cout<<ob1.x<<obj2.x;
return 0;
output
10 10
Destructing……..
Friend function
In general, only other members of a class have access to the private members of the class.
However, it is possible to allow a nonmember function access to the private members of a class
by declaring it as a friend of the class. To make a function a friend of a class, you include its
prototype in the class declaration and precede it with the friend keyword. The function is
declared with friend keyword. But while defining friend function, it does not use either keyword
friend or :: operator. A function can be a friend of more than one class. Member function of one
class can be friend functions of another class. In such cases they are defined using the scope
resolution operator.
A friend, function has following characteristics.
It is not in the scope of the class to which it has been declared as friend.
A friend function cannot be called using the object of that class. If can be invoked like a
normal function without help of any object.
It cannot access the member variables directly & has to use an object name dot
membership operator with member name.
It can be declared either in the public or the private part of a class without affecting its
meaning.
Usually, it has the object as arguments.
#include <iostream>
Using namespace std;
class A
{
int x, y;
public:
friend void display(A &obj);
void getdata()
{
cin>>x>>y;
}
};
void display(A &obj)
{
cout<<obj.x<<obj.y;
}
Int main ()
{
A a;
a.getdata();
display(a);
return 0;
}
DATA STRUCTURES
The term data structure is used to describe the way data is stored, and the term algorithm is used
to describe the way data is processed. Data structures and algorithms are interrelated. Choosing a
data structure affects the kind of algorithm you might use, and choosing an algorithm affects the
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
data structures we use. An Algorithm is a finite sequence of instructions, each of which has a
clear meaning and can be performed with a finite amount of effort in a finite length of time. No
matter what the input values may be, an algorithm terminates after executing a finite number of
instructions.
A data structure is said to be linear if its elements form a sequence or a linear list. The linear data
structures like an array, stacks, queues and linked lists organize data in linear order. A data
structure is said to be non linear if its elements form a hierarchical classification where, data
items appear at various levels.
The collections of data you work with in a program have some kind of structure or organization.
No matter how complex your data structures are they can be broken down into two fundamental
types:
• Contiguous
• Non-Contiguous.
In contiguous structures, terms of data are kept together in memory (either RAM or in a file). An
array is an example of a contiguous structure. Since each element in the array is located next to
one or two other elements. In contrast, items in a non-contiguous structure and scattered in
memory, but we linked to each other in some way. A linked list is an example of a non-
contiguous data structure. Here, the nodes of the list are linked together using pointers stored in
each node. Figure 1.6 below illustrates the difference between contiguous and non-contiguous
structures.
Contiguous structures:
Contiguous structures can be broken drawn further into two kinds: those that contain data items
of all the same size, and those where the size may differ. Figure 1.6 shows example of each kind.
The first kind is called the array. Figure 1.7 (a) shows an example of an array of numbers. In an
array, each element is of the same type, and thus has the same size.
The second kind of contiguous structure is called structure, figure 1.7(b) shows a simple
structure consisting of a person’s name and age. In a struct, elements may be of different data
types and thus may have different sizes.
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
For example, a person’s age can be represented with a simple integer that occupies two bytes of
memory. But his or her name, represented as a string of characters, may require many bytes and
may even be of varying length.
Couples with the atomic types (that is, the single data-item built-in types such as integer, float
and pointers), arrays and structs provide all the “mortar” you need to built more exotic form of
data structure, including the non-contiguous forms.
Bibliography
http://www.ddegjust.ac.in/studymaterial/mca-3/ms-17.pdf
https://www.softwaretestinghelp.com/object-oriented-programming-in-cpp/
https://www.geeksforgeeks.org/object-oriented-programming-in-cpp/
https://ambedkarcollegevasai.com/wp-content/uploads/2019/03/CPP.pdf
https://www.programmingsimplified.com/cpp/source-code/scope-resolution-operator
Inheritance:
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
Inheritance is the most powerful feature of Object Oriented programming. Inheritance is the
process of creating new classes, called derived classes from existing or bases classes. The
derived class inherits all the capabilities of the base class but can add embellishments and
refinements of its own. A class, called the derived class, can inherit the features of another class,
called the base class. Generally every base class has a list of qualities and features. The main
theme in this inheritance is to share all the common characteristics of base class to derived
classes.
Inheritance has an important feature to allow reusability. One result of reusability is the ease of
distributing class libraries. A programmer can use a class created another person or company,
and, without modifying it, derive other classes from it that are suited to particular situations.
A class can be derived from more than one classes, which means it can inherit data and functions
from multiple base classes. To define a derived class, we use a class derivation list to specify the
base class(es). A class derivation list names one or more base classes and has the form −
Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows −Live Demo
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
A derived class can access all the non-private members of its base class. Thus base-class
members that should not be accessible to the member functions of derived classes should be
declared private in the base class.
We can summarize the different access types according to - who can access them in the
following way −
A derived class inherits all base class methods with the following exceptions −
Advantages of Inheritance
The main advantage of the inheritance is that it helps in the reusability of the code. The
codes are defined only once and can be used multiple times. In java, we define the
superclass or base class in which we define the functionalities and any number of child
classes can use the functionalities at any time.
The codes are easy to debug. Inheritance allows the program to capture the bugs easily
Inheritance results in better organization of codes into smaller, simpler and simpler
compilation units.
When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.
We hardly use protected or private inheritance, but public inheritance is commonly used. While
using different type of inheritance, following rules are applied −
Public Inheritance − When deriving a class from a public base class, public members of
the base class become public members of the derived class and protected members of the
base class become protected members of the derived class. A base
class's private members are never accessible directly from a derived class, but can be
accessed through calls to the public and protected members of the base class.
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
1) Single Inheritance
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B: public A {
public:
B(){
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
cout<<"Constructor of B class";
}
};
int main() {
//Creating object of class B
B obj;
return 0;
}
Output:
Constructor of A class
Constructor of B class
2) Multilevel Inheritance
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B: public A {
public:
B(){
cout<<"Constructor of B class"<<endl;
}
};
class C: public B {
public:
C(){
cout<<"Constructor of C class"<<endl;
}
};
int main() {
//Creating object of class C
C obj;
return 0;
}
Output:
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
Constructor of A class
Constructor of B class
Constructor of C class
3) Multiple Inheritance
In multiple inheritance, a class can inherit more than one class. This means that in this type of
inheritance a single child class can have multiple parent classes.
For example:
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B {
public:
B(){
cout<<"Constructor of B class"<<endl;
}
};
class C: public A, public B {
public:
C(){
cout<<"Constructor of C class"<<endl;
}
};
int main() {
//Creating object of class C
C obj;
return 0;
}
Constructor of A class
Constructor of B class
Constructor of C class
4) Hierarchical Inheritance
In this type of inheritance, one parent class has more than one child class. For example:
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B: public A {
public:
B(){
cout<<"Constructor of B class"<<endl;
}
};
class C: public A{
public:
C(){
cout<<"Constructor of C class"<<endl;
}
};
int main() {
//Creating object of class C
C obj;
return 0;
}
Output:
Constructor of A class
Constructor of C class
5) Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance. For example, A child
and parent class relationship that follows multiple and hierarchical inheritance both can be called
hybrid inheritance.
Polymorphism:
Polymorphism is a feature of OOPs that allows the object to behave differently in different
conditions. In C++ we have two types of polymorphism:
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
1)Compile time Polymorphism – This is also known as static (or early) binding.
2) Runtime Polymorphism – This is also known as dynamic (or late) binding.
In this example, we have two functions with same name but different number of arguments.
Based on how many parameters we pass during function call determines which function is to be
called, this is why it is considered as an example of polymorphism because in different
conditions the output is different. Since, the call is determined during compile time thats why it
is called compile time polymorphism.
#include <iostream>
using namespace std;
class Add {
public:
int sum(int num1, int num2){
return num1+num2;
}
int sum(int num1, int num2, int num3){
return num1+num2+num3;
}
};
int main() {
Add obj;
//This will call the first function
cout<<"Output: "<<obj.sum(10, 20)<<endl;
//This will call the second function
cout<<"Output: "<<obj.sum(11, 22, 33);
return 0;
}
Output:
Output: 30
Output: 66
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.
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
Example:
#include<iostream>
class Complex {
private:
public:
Complex res;
return res;
void print() { cout << real << " + i" << imag << endl; }
};
int main()
c3.print();
}
Output
12 + i9
1) For operator overloading to work, at least one of the operands must be a user defined class
object.
3) Conversion Operator: We can also write conversion operators that can be used to convert one
type to another type.
4) Any constructor that can be called with a single argument works as a conversion constructor,
means it can also be used for implicit conversion to the class being constructed
2) Runtime Polymorphism
Function overriding is an example of Runtime polymorphism. Function Overriding: When
child class declares a method, which is already present in the parent class then this is called
function overriding, here child class overrides the parent class.
In case of function overriding we have two definitions of the same function; one is parent class
and one in child class. The call to the function is determined at runtime to decide which
definition of the function is to be called, that’s the reason it is called runtime polymorphism.
#include <iostream>
using namespace std;
class A {
public:
void disp(){
cout<<"Super Class Function"<<endl;
}
};
class B: public A{
public:
void disp(){
cout<<"Sub Class Function";
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
}
};
int main() {
//Parent class object
A obj;
obj.disp();
//Child class object
B obj2;
obj2.disp();
return 0;
}
Output:
Virtual Function:
When we declare a function as virtual in a class, all the sub classes that override this function
have their function implementation as virtual by default (whether they mark them virtual or
not). Why we declare a function virtual? To let compiler know that the call to this function
needs to be resolved at runtime (also known as late binding and dynamic linking) so that the
object type is determined and the correct version of the function is called.
Let’s take an example to understand what happens when we don’t mark an overridden
function as virtual.
See the problem here. Even though we have the parent class pointer pointing to the instance
(object) of child class, the parent class version of the function is invoked.
You may be thinking why I have created the pointer, I could have simply created the object of
child class like this: Dog obj; and assigned the Dog instance to it. Well, in this example I have
only one child class but when we a big project having several child classes, creating the object of
child class separately is not recommended as it increases the complexity and the code become
error prone. More clarity to this after this example.
Output:
#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
virtual void animalSound(){
cout<<"This is a generic Function";
}
};
//child class or sub class or derived class
class Dog : public Animal{
public:
void animalSound(){
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}
Output:
Woof
Bibliography
http://www.cplusplus.com/doc/tutorial/polymorphism/
https://beginnersbook.com/2017/08/cpp-function-overloading/
https://www.geeksforgeeks.org/operator-overloading-c/
https://web.cs.dal.ca/~jin/3132/lectures/OOP-07.pdf
RGPV Questions
What is Object oriented Programming? Explain its Features. RGPV Nov 2019
LAKSHMI NARAIN GROUP OF COLLEGES, BHOPAL
What are virtual Functions? What is use of it? Give an example. RGPV May 2019
What is the use of Operator Overloading? Write a Program to overload Pre and post Operator
RGPV May 2018
What is the benefits of copy constructor? Explain with Suitable Example RGPV Nov 2018
Explain Following
Friend Function
Scope Resolution Operator RGPV Nov 2019