Professional Documents
Culture Documents
C++ UNIT-III
C++ UNIT-III
UNIT III:
What is a Class?
A class is a blueprint for the object. A C++ class combines data and methods for manipulating
the data into one. Classes also determine the forms of objects. The data and methods
contained in a class are known as class members. A class is a user-defined data type. To
access the class members, we use an instance of the class.
A class be a prototype for a house. It shows the location and sizes of doors, windows, floors,
etc. From these descriptions, we can construct a house. The house becomes the object. It's
possible to create many houses from the prototype. Also, it's possible to create many objects
from a class.
In the above figure, we have a single house prototype. From this prototype, we have created
two houses with different features.
Create a Class
A class is defined in C++ using keyword class followed by the name of the class.
The body of the class is defined inside the curly brackets and terminated by a semicolon at
the end.
class className {
// some data (private)
// some functions (public)
};
riteshkandarics@gmail.com iamriteshkandari 9259069231
For example,
class Room {
public:
double length;
double breadth;
double height;
double calculateArea()
{
return length * breadth;
}
double calculateVolume()
{
return (length * breadth * height);
}
};
Here, we defined a class named Room.
The variables length, breadth, and height declared inside the class are known as data
members. And, the functions calculateArea() and calculateVolume() are known
as member functions of a class.
C++ Objects
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, we need
to create objects.
We can create objects of Room class (defined in the above example) as follows:
// create objects
Room room1, room2;
}
Here, two objects room1 and room2 of the Room class are created in main ().
riteshkandarics@gmail.com iamriteshkandari 9259069231
Output
Area of Room = 1309
Volume of Room = 25132.8
riteshkandarics@gmail.com iamriteshkandari 9259069231
In this program, we have used the Room class and its object room1 to calculate the area and
volume of a room.
In main(), we assigned the values of length, breadth, and height with the code:
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
We then called the functions calculateArea() and calculateVolume() to perform the
necessary calculations.
Note: the use of the keyword public in the program. This means the members are public and
can be accessed anywhere from the program.
As per our needs, we can also create private members using the private keyword. The
private members of a class can only be accessed from within the class. For example,
class Test {
private:
int a;
void function1() { }
public:
int b;
void function2() { }
}
Here, a and function1() are private. Thus they cannot be accessed from outside the class.
On the other hand, b and function2() are accessible from everywhere in the program.
Output
Area of Room = 1309
Volume of Room = 25132.8
The above example is nearly identical to the first example, except that the class variables are
now private.
Since the variables are now private, we cannot access them directly from main(). Hence,
using the following code would be invalid:
// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;
Instead, we use the public function getData() to initialize the private variables via the
function parameters double len, double brth, and double hgt.
Constructor
A constructor (have the same name as that of the class) is a member function which is
automatically used to initialize the object of the class type with legal initial value.
Special Characteristics of Constructor:
1) These are called automatically when the objects are created.
2) Return type (not even void) cannot be specify for constructor.
3) These cannot be static.
riteshkandarics@gmail.com iamriteshkandari 9259069231
For example,
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
Here, the function Wall() is a constructor of the class Wall. Notice that the constructor
• has the same name as the class,
• is public
Output
Creating a Wall
Length = 5.5
Here, when the wall1 object is created, the Wall() constructor is called. This sets
the length variable of the object to 5.5.
Note: If we have not defined a constructor in our class, then the C++ compiler will
automatically create a default constructor with an empty code and no parameters.
constructor.
Syntax Of User-defined Copy Constructor:
Class_name(const class_name &old_object);
Output
Area of Wall 1: 90.3
Area of Wall 2: 90.3
In this program, we have used a copy constructor to copy the contents of one object
of the Wall class to another. The code of the copy constructor is:
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}
Notice that the parameter of this constructor has the address of an object of
the Wall class.
We then assign the values of the variables of the first object to the corresponding
variables of the second object. This is how the contents of the object are copied.
In main(), we then create two objects wall1 and wall2 and then copy the contents of
the first object to the second with the code
Wall wall2 = wall1;
riteshkandarics@gmail.com iamriteshkandari 9259069231
Note: A constructor is primarily used to initialize objects. They are also used to run a
default code when an object is created.
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can
be defined only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).
Let's see an example of constructor and destructor in C++ which is called
automatically.
#include <iostream.h>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
void main()
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
}
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So
instance is not required to access the static members. In C++, static can be field,
method, constructor, class, properties, operator and event.
riteshkandarics@gmail.com iamriteshkandari 9259069231
class student
{
static int count; //declaration within the class
};
The static data member is defined outside the class as follows:
int student :: count; //defining outside the class
For Example:
#include <iostream.h>
using namespace std;
class item
{
static int count;
riteshkandarics@gmail.com iamriteshkandari 9259069231
int no;
public:
void getdata(int a)
{
no=a;
count++;
}
void getcount()
{
Cout<<”Value of count=”<<count;
}
};
int item :: count;
void main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<”After reading data<<endl”;
a.getcount();
b.getcount();
c.getcount();
}
For Example:
#include <iostream.h>
using namespace std;
class student
riteshkandarics@gmail.com iamriteshkandari 9259069231
{
static int count;
int rollno,marks;
public:
void enter(int r,int n)
{
rollno=r;
marks=m;
count++;
}
void show()
{
cout<<”Roll No=”<<rollno;
cout<<”Marks=”<<marks;
}
static void showcount()
{
cout<<”Count=”<<count;
}
};
int student :: count;
void main()
{
student s1,s2,s3;
s1.enter(1001,99);
student :: showcount();
s2.enter(1002,88);
student :: showcount();
s3.enter(1003,77);
student :: showcount();
s1.show();
s2.show();
s3.show();
}
Friend Function
Friend functions of the class are granted access to private and protected members of
the class in C++. They are defined outside the class’ scope. Friend functions are not
riteshkandarics@gmail.com iamriteshkandari 9259069231
member functions of the class. The friend function is declared using the friend
keyword inside the body of the class.
Friend Function Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
By using the keyword, the ‘friend’ compiler knows that the given function is a friend
function.
We declare friend function inside the body of a class, starting with the keyword friend
to access the data. We use them when we need to operate between two different
classes at the same time.
Characteristics:
1) It is not in the scope of the class of which it is a friend.
2) We cannot call a friend function using the object of the class.
3) It can be called like a normal function. i.e. without any object.
4) It accept object as its argument.
Inline Function:
When the program executes the function call instruction the CPU stores the memory
address of the instruction following the function call, copies the arguments of the
function on the stack and finally transfers control to the specified function. The CPU
then executes the function code, stores the function return value in a predefined
memory location/register and returns control to the calling function. This can become
overhead if the execution time of function is less than the switching time from the
caller function to called function (callee). For functions that are large and/or perform
complex tasks, the overhead of the function call is usually insignificant compared to
the amount of time the function takes to run. However, for small, commonly-used
functions, the time needed to make the function call is often a lot more than the time
needed to actually execute the function’s code. This overhead occurs for small
functions because execution time of small function is less than the switching time.
C++ provides an inline functions to reduce the function call overhead.
Inline function is a function that is expanded in line when it is called. When the inline
function is called whole code of the inline function gets inserted or substituted at the
point of inline function call. This substitution is performed by the C++ compiler at
compile time. Inline function may increase efficiency if it is small.
Example:
#include <iostream.h>
using namespace std;
inline int cube(int s)
riteshkandarics@gmail.com iamriteshkandari 9259069231
{
return s*s*s;
}
void main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
}
Function Overloading
Overloading means to use the same thing for different purposes. In C++ overload
function refers to a function having one name and more than one distinct meaning.
Note: A function argument list is also known as function signature. For overloading a
function declare & define all the functions with the same name but different
signatures separately.
Example:
float volume (float,float); //prototype 1
float volume (float,int); //prototype 2
float volume (float,float,float); //prototype 3
Example:
#include <iostream.h>
using namespace std;
void cal(int,int);
riteshkandarics@gmail.com iamriteshkandari 9259069231
void cal(float,float);
void cal(int b,int h)
{
int area;
area=(b*h)/2;
cout<<”Area of triangle=”<<area;
}
void cal(float x,float y)
{
float result;
result=x*y;
cout<<”Area of rectangle=”<<result;
}
void main()
{
cal(10,20);
cal(2.5,6.5);
}
Inheritance
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or
modify the attributes and behaviors which are defined in other class.
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.
Types of Inheritance
C++ supports five types of inheritance:
1) Single inheritance
riteshkandarics@gmail.com iamriteshkandari 9259069231
2) Multiple inheritance
3) Hierarchical inheritance
4) Multilevel inheritance
5) Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}
Where,
derived_class_name: It is the name of the derived class.
Visibility mode: The visibility mode specifies whether the features of the base class
are publicly inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.
• When the base class is privately inherited by the derived class, public members of
the base class becomes the private members of the derived class. Therefore, the
public members of the base class are not accessible by the objects of the derived
class only by the member functions of the derived class.
• When the base class is publicly inherited by the derived class, public members of
the base class also become the public members of the derived class. Therefore, the
public members of the base class are accessible by the objects of the derived class
as well as by the member functions of the base class.
Note:
• In C++, the default mode of visibility is private.
riteshkandarics@gmail.com iamriteshkandari 9259069231
• The private members of the base class are never inherited.
Where 'A' is the base class, and 'B' is the derived class
For Example:
#include <iostream.h>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
void main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
}
class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
scout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
void main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();
}
Output:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
In the above example, class 'C' inherits two base classes 'A' and 'B' in a public mode.
Output:
error: reference to 'display' is ambiguous
display();
o The above issue can be resolved by using the class resolution operator with the
function. In the above example, the derived class code can be rewritten as:
riteshkandarics@gmail.com iamriteshkandari 9259069231
class C : public A, public B
{
void view()
{
A :: display(); // Calling the display() function of class A.
B :: display(); // Calling the display() function of class B.
}
};
#include <iostream.h>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
riteshkandarics@gmail.com iamriteshkandari 9259069231
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
void main() {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
}
Output:
Eating...
Barking...
Weeping...
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
riteshkandarics@gmail.com iamriteshkandari 9259069231
void get_a()
{
cout << "Enter the value of 'a' : " << endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
cout << "Enter the value of 'b' : " << endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
cout << "Enter the value of c is : " << endl;
cin>>c;
}
};
Hierarchical Inheritance
Hierarchical inheritance is defined as the process of deriving more than one class from
a base class.
Operator Overloading
In C++, it can add special features to the functionality and behaviour of already existing
operators like athematic and other operations. The mechanism of giving special
meaning to an operator is known as operator overloading. For example, we can
overload an operator ‘+’ in a class like string to concatenate two strings by just using
+.
Output
Count: 6
Here, when we use ++count1;, the void operator ++ () is called. This increases
the value attribute for the object count1 by 1.
riteshkandarics@gmail.com iamriteshkandari 9259069231
Example: ++ Operator (Unary Operator) Overloading
// Overload ++ when used as prefix and postfix
#include <iostream.h>
using namespace std;
class count {
private:
int value;
public:
// Constructor to initialize count to 5
count() {
value=5;
}
// Overload ++ when used as prefix
void operator ++ () {
++value;
}
// Overload ++ when used as postfix
void operator ++ (int) {
value++;
}
void display() {
cout << "Count: " << value << endl;
}
};
void main() {
count count1;
// Call the "void operator ++ (int)" function
count1++;
count1.display();
// Call the "void operator ++ ()" function
++count1;
count1.display();
}
Output
Count: 6
Count: 7
#include <iostream>
using namespace std;
class sum {
int a;
public:
riteshkandarics@gmail.com iamriteshkandari 9259069231
void getdata(int x)
{
a=x;
}
int operator+(sum s1);
};
int sum::operator+(sum s1)
{
int c;
c=a+s1.a;
return c;
}
void main()
{
sum s2,s3;
s2.getdata(10);
s3.getdata(20);
int c=s2+s3;
cout<<"value="<<c;
}
#include <iostream>
using namespace std;
class sum {
int a,b;
public:
void getdata(int x,int y)
{
a=x;
b=y;
}
sum operator+(sum s1);
void display();
};
sum sum::operator+(sum s1)
{
sum c;
c.a=a+s1.a;
c.b=b+s1.b;
return (c);
riteshkandarics@gmail.com iamriteshkandari 9259069231
}
void sum::display()
{
cout<<a<<" j"<<b;
}
void main()
{
sum s2,s3,s4;
s2.getdata(10,20);
s3.getdata(50,60);
s4=s2+s3;
s4.display();
}
Output:
Eating bread...
#include <iostream.h>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
riteshkandarics@gmail.com iamriteshkandari 9259069231
};
void main() {
Animal *a;
Dog d;
a=&d;
a->eat(); // early binding
}
Output: Eating
In the above example the object is of Derived class still base class method is called.
This happen due to early binding.
#include <iostream.h>
using namespace std;
class Animal {
public:
virtual void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
void main() {
Animal *a;
Dog d;
a=&d;
a->eat(); // late binding
}
#include <iostream.h>
using namespace std;
class Animal {
public:
virtual void eat()=0; //pure virtual function
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
void main() {
Animal *a;
Dog d;
a=&d;
a->eat(); // late binding
}
Output:
101 Sonoo 890000
102 Nakul 59000