Professional Documents
Culture Documents
UNIT III
Object & Classes, Scope Resolution Operator, Constructors & Destructors, Friend Functions,
Inheritance, Polymorphism, Overloading Functions & Operators, Types of Inheritance, Virtual
functions. Introduction to Data Structures.
The classes are the most important feature of C++ that leads to Object Oriented programming.
Class is a user defined data type, which holds its own data members and member functions,
which can be accessed and used by creating instance of that class.
The variables inside class definition are called as data members and the functions are called
member functions.
For example : Class of birds, all birds can fly and they all have wings and beaks. So here flying is
a behavior and wings and beaks are part of their characteristics. And there are many different
birds in this class with different names but they all posses this behavior and characteristics.
Similarly, class is just a blue print, which declares and defines characteristics and behavior,
namely data members and member functions respectively. And all objects of this class will
share these characteristics and behavior.
Primary purpose of a class is to held data/information. This is achieved with attributes which is
also know as data members.
The member functions determine the behavior of the class i.e. provide definition for supporting
various operations on data held in form of an object.
Definition of a class
Syntax:
Class class_name
{
Data Members;
Methods;
}
1. Class name must start with an uppercase letter (Although this is not mandatory). If class
name is made of more than one word, then first letter of each word must be in
uppercase.
Example,
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
The private keyword makes data and functions private. Private data and functions can be
accessed only from inside the same class.
The public keyword makes data and functions public. Public data and functions can be accessed
out of the class.
Objects
Class is mere a blueprint or a template. No storage is assigned when we define a class. Objects
are instances of class, which holds the data variables declared in class and the member
functions work on these class objects.
Each object has different data variables. Objects are initialised using special class functions
called Constructors.
Example:
class Abc
{
int x;
void display(){} //empty function
};
in main()
{
Abc obj; // Object of class Abc created
}
The public data members of objects of a class can be accessed using the direct member access
operator (.).
Example −
#include <iostream>
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
Example -
class Test
{
private:
int data1;
float data2;
public:
void function1()
{ data1 = 2; }
float function2()
{
data2 = 3.5;
return data2;
}
};
int main()
{
Test o1, o2;
}
Here, two objects o1 and o2 of Test class are created.
In the above class Test, data1 and data2 are data members and function1() and function2() are
member functions.
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
Scope resolution operator(::) is used to define a function outside a class or when we want to
use a global variable but also has a local variable with same name.
#include <iostream>
char c = 'a'; // global variable
int main() {
char c = 'b'; //local variable
return 0;
}
Output of program:
Local variable: b
Global variable: a
Scope resolution operator in class
#include <iostream>
using namespace std;
class programming {
public:
void output(); //function declaration
};
void programming::output() {
cout << "Function defined outside the class.\n";
}
int main() {
programming x;
x.output();
return 0;
}
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
Constructors
Constructors is a special member functions of class and it is used to initialize the objects of its
class. It is treated as a special member function because its name is the same as the class name.
These constructors get invoked whenever an object of its associated class is created. It is
named as “constructor” because it constructs the value of data member of a class. Initial values
can be passed as arguments to the constructor function when the object is declared.
1.Default Constructor
Default constructor is the constructor which doesn’t take any argument. It has no parameter
but programmer can write some initialization statement there.
Syntax:
class_name()
{
// Constructor Definition ;
}
#include <iostream>
using namespace std;
class Calc
{
int val;
public:
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
Calc()
{
val = 20;
}
};
int main()
{
Calc c1;
cout << c1.val;
}
2. Parameterized Constructor
A default constructor does not have any parameter, but programmers can add and use
parameters within a constructor if required. This helps programmers to assign initial values to
an object at the time of creation.
Example-
#include <iostream>
using namespace std;
class Calc
{
int val2;
public:
Calc(int x)
{
val2=x;
}
};
int main()
{
Calc c1(10);
Calc c2(20);
Calc c3(30);
cout << c1.val2;
cout << c2.val2;
cout << c3.val2; }
3. Copy Constructor
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
C++ provides a special type of constructor which takes an object as argument, and is used to
copy values of data members of one object into other object. In this case, copy constructors are
used to declare and initialize object from another object.
#include <iostream>
using namespace std;
class CopyCon
{
int a, b;
public:
CopyCon(int x, int y)
{
a = x;
b = y;
cout << "\nHere is the initialization of Constructor";
}
void Display()
{
cout << "\nValues : \t" << a << "\t" << b;
}
};
void main()
{
CopyCon Object(30, 40); //Copy Constructor
CopyCon Object2 = Object;
Object.Display();
Object2.Display();
}
Destructors:
As the name implies, destructors are used to destroy the objects that have been created by the
constructor within the C++ program. Destructor names are same as the class name but they are
preceded by a tilde (~). It is a good practice to declare the destructor after the end of using
constructor.
}
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
The destructor neither takes a argument nor returns any value and the compiler implicitly
invokes upon the exit from the program for cleaning up storage that is no longer accessible.
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. Even though the prototypes for friend functions
appear in the class definition, friends are not member functions.
To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend
class class_name
{
... .. ...
friend return_type function_name(argument/s);
... .. ...
}
Example-
#include<iostream.h>
#include<conio.h>
class base {
int val1, val2;
public:
void get() {
cout << "Enter two values:";
cin >> val1>>val2;
}
friend float mean(base b);
};
float mean(base b) {
return float(b.val1 + b.val2) / 2;
}
void main() {
clrscr();
base obj;
obj.get();
cout << "\n Mean value is : " << mean(obj);
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
getch();
}
Output-
Enter two values: 10, 20
Mean Value is: 15
Example-
#include <iostream.h>
using namespace std;
class A{
private:
int x;
public:
A(){
x = 0;
}
friend int show( A ); // declaring friend function
};
Output :
Value of a : 5
Polymorphism
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and morphs means forms. So polymorphism means many forms.
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(10, 20, 30);
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
}
Output
30
60
Operators Overloading
Operator overloading is used to overload or redefine most of the operators available in C++. It
is used to perform operation on user define data type.
Almost any operator can be overloaded in C++. However there are few operator which can not
be overloaded. Operator that are not overloaded are follows
scope operator - ::
sizeof
member selector - .
member pointer selector - *
ternary operator - ?:
Operator Overloading Syntax
Example
Let's see the simple example of operator overloading in C++. In this example, void operator ++
() operator function is defined (inside Test class).
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test()
{
Num=8;
}
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;
}
Output:
Method Overriding :
Define any method in both base class and derived class with same name, same parameters or
signature, this concept is known as method overriding.
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
In below example same method "show()" is present in both base and derived class with same
name and signature.
class Base
{
public:
void show()
{
cout<<"Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"Derived Class";
}
}
int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Ocuurs
d.show();
getch();
}
Output
Base class
Derived Class
Inheritance
The technique of deriving a new class from an old one is called inheritance. The old class is
referred to as base class and the new class is referred to as derived class or sub class.
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
Inheritance concept allows programmers to define a class in terms of another class, which
makes creating and maintaining application easier. When writing a new class, instead of writing
new data member and member functions all over again, programmers can make a bonding of
the new class with the old one that the new class should inherit the members of the existing
class. A class can get derived from one or more classes, which means it can inherit data and
functions from multiple base classes.
Visibility mode is used in inheritance of C++ to show or relate how base classes are viewed with
respect to derived class. When one class gets inherited from another, visibility mode is used to
inherit all the public and protected members of the base class. Private members never get
inherited and hence do not take part in visibility. By default, visibility mode remains “private”.
Single Inheritance
In single inheritance there is only one base class and one derived class. The Derived class gets
inherited from its base class. This is the simplest form of inheritance.
Example-
Step 1: Start the program.
Step 2: Declare the base class emp.
Step 3: Define and declare the function get() to get the employee details.
Step 4: Declare the derived class salary.
Step 5: Declare and define the function get1() to get the salary details.
Step 6: Define the function calculate() to find the net pay.
Step 7: Define the function display().
Step 8: Create the derived class object.
Step 9: Read the number of employees.
Step 10: Call the function get(),get1() and calculate() to each employees.
Step 11: Call the display().
#include<iostream.h>
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
#include<conio.h>
class emp {
public:
int eno;
char name[20], des[20];
void get() {
cout << "Enter the employee number:";
cin>>eno;
cout << "Enter the employee name:";
cin>>name;
cout << "Enter the designation:";
cin>>des;
}
};
void calculate() {
np = bp + hra + da - pf;
}
void display() {
cout << eno << "\t" << name << "\t" << des << "\t" << bp << "\t" << hra << "\t" << da << "\t"
<< pf << "\t" << np << "\n";
}
};
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
void main() {
int i, n;
char ch;
salary s[10];
clrscr();
cout << "Enter the number of employee:";
cin>>n;
for (i = 0; i < n; i++) {
s[i].get();
s[i].get1();
s[i].calculate();
}
cout << "\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";
for (i = 0; i < n; i++) {
s[i].display();
}
getch();
}
Multiple Inheritance -
In this type of inheritance, a single derived class may inherit from two or more base classes
Example:
#include <iostream>
using namespace std;
class stud {
protected:
int roll, m1, m2;
public:
void get()
{
cout << "Enter the Roll No.: "; cin >> roll;
cout << "Enter the two highest marks: "; cin >> m1 >> m2;
}
};
class extracurriculam
{
protected:
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
int xm;
public:
void getsm()
{
cout << "\nEnter the mark for Extra Curriculam Activities: "; cin >> xm;
}
};
Hierarchical Inheritance
In this type of inheritance, multiple derived classes get inherited from a single base class
Class base_classname
{
properties;
methods;
};
Class derived_class1 : visibility_mode base_classname
{
properties;
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
methods;
};
class derived_class2 : visibility_mode base_classname
{
properties;
methods;
};
... ... ... ... ... ...
class derived_classN : visibility_mode base_classname
{
properties;
methods;
};
#include <iostream>
#include <string.h>
using namespace std;
class member
{
char gender[10];
int age;
public:
void get()
{
cout << "Age: ";
cin >> age;
cout << "Gender: ";
cin >> gender;
}
void disp()
{
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
}
};
{
member::get();
cout << "Class: ";
cin >> level;
}
void disp2()
{
member::disp();
cout << "Level: " << level << endl;
}
};
void disp3()
{
member::disp();
cout << "Salary: Rs." << salary << endl;
}
};
int main()
{
member M;
staff S;
stud s;
cout << "Student" << endl;
cout << "Enter data" << endl;
s.getdata();
cout << endl << "Displaying data" << endl;
s.disp();
cout << endl << "Staff Data" << endl;
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
Multilevel Inheritance
The classes can also be derived from the classes that are already derived. This type of
inheritance is called multilevel inheritance.
#include <iostream>
using namespace std;
class base {
public:
void display1()
{
cout << "\nBase class content.";
}
};
class derived : public base {
public:
void display2()
{
cout << "1st derived class content.";
}
};
Virtual function.
- A virtual function is a member function that is declared within a base class and redefined by a
derived class. To create virtual function, precede the function’s declaration in the base class
with the keyword virtual. When a class containing virtual function is inherited, the derived class
redefines the virtual function to suit its own needs.
- Base class pointer can point to derived class object. In this case, using base class pointer if we
call some function which is in both classes, then base class function is invoked. But if we want
to invoke derived class function using base class pointer, it can be achieved by defining the
function as virtual in base class, this is how virtual functions support runtime polymorphism.
B oB;
pA = &oB;
pA→show();
return 0;
}
- Output is 2 since pA points to object of B and show() is virtual in base class A.
3. When we define a data structure we are in fact creating a new data type of our own.
i.e. using predefined types or previously user defined types.
Such new types are then used to reference variables type within a program
Data Definition
Data Definition defines a particular data with following characteristics.
Data Object
Data Object represents an object having a data.
Data Type
A data type is a type of data , a better definition of a data type is a data storage format
that can contain a specific type or range of values.
When computer programs store data in variables, each variable must be assigned a
specific data type. Some common data types include integers, floating point
numbers,characters, strings, and arrays.
Data type is way to classify various types of data such as integer, string etc. which
determines the values that can be used with the corresponding type of data, the type of
operations that can be performed on the corresponding type of data. Data type of two
types −
Those data types for which a language has built-in support are known as Built-in Data
types. For example, most of the languages provides following built-in data types.
Integers
Boolean (true, false)
Floating (Decimal numbers)
Character and Strings
Derived Data Type
Those data types which are implementation independent as they can be implemented
in one or other way are known as derived data types. These data types are normally
built by combination of primary or built-in data types and associated operations on
them. For example −
List
Array
Stack
Queue
Basic Operations
The data in the data structures are processed by certain operations. The particular data
structure chosen largely depends on the frequency of the operation that needs to be
performed on the data structure.
Traversing
Searching
Insertion
Deletion
Sorting
Merging
A data structure is a method for organizing and storing data, which would allow efficient
data retrieval and usage. Linear data structure is a structure that organizes its data
BTech- I Yr ..BASIC COMPUTER ENGINEERING (BT- 2005)
elements one after the other. Linear data structures are organized in a way similar to
how the computer‘s memory is organized. Nonlinear data structures are constructed by
attaching a data element to several other data elements in such a way that it reflects a
specific relationship among them. Nonlinear data structures are organized in a different
way than the computer‘s memory.
Linear data structures organize their data elements in a linear fashion, where data
elements are attached one after the other. Data elements in a liner data structure are
traversed one after the other and only one element can be directly reached while
traversing. Linear data structures are very easy to implement, since the memory of the
computer is also organized in a linear fashion. Some commonly used linear data
structures are arrays, linked lists, stacks and queues. An arrays is a collection of data
elements where each element could be identified using an index. A linked list is a
sequence of nodes, where each node is made up of a data element and a reference to
the next node in the sequence. A stack is actually a list where data elements can only
be added or removed from the top of the list. A queue is also a list, where data elements
can be added from one end of the list and removed from the other end of the list.
In nonlinear data structures, data elements are not organized in a sequential fashion. A
data item in a nonlinear data structure could be attached to several other data elements
to reflect a special relationship among them and all the data items cannot be traversed
in a single run. Data structures like multidimensional arrays, trees and graphs are some
examples of widely used nonlinear data structures. A multidimensional array is simply a
collection of one-dimensional arrays. A tree is a data structure that is made up of a set
of linked nodes, which can be used to represent a hierarchical relationship among data
elements. A graph is a data structure that is made up of a finite set of edges and
vertices. Edges represent connections or relationships among vertices that stores data
elements.
Main difference between linear and nonlinear data structures lie in the way they
organize data elements. In linear data structures, data elements are organized
sequentially and therefore they are easy to implement in the computer‘s memory. In
nonlinear data structures, a data element can be attached to several other data
elements to represent specific relationships that exist among them. Due to this
nonlinear structure, they might be difficult to be implemented in computer‘s linear
memory compared to implementing linear data structures. Selecting one data structure
type over the other should be done carefully by considering the relationship among the
data elements that needs to be stored.