module 4: introduction to class & object
TRANSCRIPT
Module 4: Introduction to class & Object
The classes are the most important feature of C++ that leads to Object Oriented
programming.
A class is a blueprint for the object.
Note: We can think of class as a sketch (prototype) of a house. It contains all the details
about the floors, doors, windows etc. Based on these descriptions we build the house.
House is the object. As, many houses can be made from the same description, we can
create many objects from a class.
When you define a class, you define a blueprint for a data type. This doesn't actually
define any data, but it does define what the class name means, that is, what an object of
the class will consist of and what operations can be performed on such an object.
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 (object) of that class.
Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
defines the properties and behaviour of the objects in a Class.
An Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the name of class. The body
of class is defined inside the curly brackets and terminated by a semicolon at the end.
KTUNOTES.IN
Downloaded from Ktunotes.in
Declaring 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, you need to create objects.
Syntax:
ClassName ObjectName;
Accessing data members and member functions:
The data members and member functions of class can be accessed using the dot(‘.’)
operator with the object. For example if the name of object is obj and you want to
access the member function with the name displayName() then you will have to write
obj.displayName() .
Defining Member Functions
There are 2 ways to define a member function:
o Inside class definition
#include<iostream>
using namespace std;
class student
{ int id,age;
char name[100];
public:
void readdata()
{
cout<<"enter the id:";
cin>>id;
cout<<"enter the name:";
cin>>name;
cout<<"enter the age:";
cin>>age;
}
void dispay()
{ cout<<” Details:\n”;
cout<<"ID: "<<id;
cout<<"\nName: "<<name;
cout<<"\n Age : "<<age;
}
};
int main()
{ student a;
a.readdata();
a.dispay();
return 0;
}
Data members
Member
Function
Member Function
Creating Object of student
Accessing member functions
KTUNOTES.IN
Downloaded from Ktunotes.in
o Outside class definition
To define a member function outside the class definition we have to use the scope
resolution :: operator along with class name and function name.
And function declaration should be there inside the class
Access Modifiers in C++
Access modifiers are used to implement important feature of Object Oriented
Programming known as Data Hiding. Access modifiers or Access Specifiers in a class
are used to set the accessibility of the class members. That is, it sets some restrictions on
the class members not to get directly accessed by the outside functions.
There are 3 types of access modifiers available in C++:
Public
Private
Protected
#include<iostream>
using namespace std;
class square
{
int a,area,perimeter;
public:
void readdata()
{
cout<<"ënter the length :";
cin>>a;
}
int calc_area()
{
area= a*a;
return area;
}
void display()
{
cout<<"area of the square is"<<calc_area();
}
};
int main()
{
square s;
s.readdata();
s.display();
}
#include<iostream>
using namespace std;
class square
{
int a,area,perimeter;
public:
void readdata()
{
cout<<"ënter the length :";
cin>>a;
}
int calc_area()
{
area= a*a;
return area;
}
void display(); //function declaration
};
void square::display()
{
cout<<"area of the square is"<<calc_area();
}
int main()
{
square s;
s.readdata();
s.display();
}
Member
functions
are
defined
inside
the class
definitio
n
Member
functions
display is
defined outside
the class
definition, with
function
declared inside
the class
Member function defined inside the class Member function defined outside the class
KTUNOTES.IN
Downloaded from Ktunotes.in
Note: If we do not specify any access modifiers for the members inside the class then
by default the access modifier for the members will be Private
Public: All the class members declared under public will be available to everyone. The
data members and member functions declared public can be accessed by other classes
too. The public members of a class can be accessed from anywhere in the program using
the direct member access operator (.) with the object of that class.
In the above program the data member radius r is public so we are allowed to access it
outside the class.
Private:
The class members declared as private can be accessed only by the functions inside the
class. They are not allowed to be accessed directly by any object or function outside the
class. Only the member functions or the friend functions are allowed to access the
private data members of a class.
Example:
The output of below program will be a compile time error because we are not allowed to
access the private data members of a class directly outside the class.
#include<iostream>
using namespace std;
class circle
{
public:
int r;
void readdata()
{
cout<<"Enter the radius: ";
cin>>r;
}
};
int main()
{
circle c;
c.readdata();
area=3.14*c.r*c.r;
cout<<"area of the circle is :"<<area;
return 0;
}
Data member and
member function is
declared as public
That is why both members
are accessible from
outside the class KTUNOTES.IN
Downloaded from Ktunotes.in
However we can access the private data members of a class indirectly using the public
member functions of the class.
#include<iostream>
using namespace std;
class circle
{
int r;
public:
void readdata()
{
cout<<"Enter the radius: ";
cin>>r;
}
};
int main()
{
circle c;
c.readdata();
area=3.14*c.r*c.r;
cout<<"area of the circle is :"<<area;
return 0;
}
r is a private data member. If we do
not specify any access modifiers ,then
by default the access modifier will be
Private.Or you can write
private: int r
Accessing private
member r
#include<iostream>
using namespace std;
class circle
{
int r;
public:
void readdata()
{
cout<<"Enter the radius: ";
cin>>r;
}
void calc_area()
{
cout<<”area of the circle is: “<<3.14*r*r;
}
};
int main()
{
circle c;
c.readdata();
c.calc_area();
return 0;
}
Member function can access
private data member r
KTUNOTES.IN
Downloaded from Ktunotes.in
Protected: Protected access modifier is similar to that of private access modifiers, the
difference is that the class member declared as Protected are inaccessible outside the class
but they can be accessed by any subclass (derived class) of that class.// not in syllabus
Note: Declaring a friend function is a way to give private access to a non-member
function.
Friend class and function in C++
Friend Class A friend class can access private and protected members of other class
in which it is declared as friend. It is sometimes useful to allow a particular class to
access private members of other class
Friend Function Like friend class, a friend function can be given special grant to access
private and protected members. A friend function can be:
o A method of another class
o A global function
#include<iostream>
using namespace std;
class circle
{
int r;
public:
void readdata()
{
cout<<"Enter the radius: ";
cin>>r;
}
friend class shape;
};
class shape
{ //class definition of shape };
Now class shape
can access private
members of class
circle
#include<iostream>
using namespace std;
class circle
{
int r;
public:
void getdata()
{
cout<<"Enter the radius of circle: ";
cin>>r;
}
friend int calc( circle c);
};
int calc( circle c)
{
circle c;
c.getdata();
cout<<"area of the circle is :"<<3.14*c.r*c.r;
return 0;
}
Function calc is
declared as a
friend of circle
So that method calc can
access the private member r
of circle
KTUNOTES.IN
Downloaded from Ktunotes.in
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. too many functions or external
classes are declared as friends of a class with protected or private data, it lessens the
value of encapsulation of separate classes in object-oriented programming.
2) Friendship is not mutual. If a class A is friend of B, then B doesn’t become friend
of A automatically.
3) Friendship is not inherited
Constructors
Constructer is a special type of member function that initialises an object automatically
when it is created
The compiler calls the constructor whenever an object is created
Constructors have the same name as the class
Constructor can be defined inside or outside the class definition.
A constructer is defined without a return type
By deafault constructors are defined in the public section of class, so that constructor is
called automatically when an object is created outside the class
A constructer is defined without a return type
#include<iostream>
using namespace std;
class cube
{
int length,volume;
public:
cube()
{
cout<<”This is a cube”;
length=10;
}
void volume()
{
volume=length*length*length;
cout<<”volume is “<<volume;
}
};
int main()
{
cube c;
c.volume();
return 0;
}
The constructor get called
automatically while creating
object and value of length is
initialised to 10
OUTPUT
This is a cube
volume is 1000
KTUNOTES.IN
Downloaded from Ktunotes.in
There are 3 types of constructors:
Default constructors
Parameterized constructors
Copy constructors
Default constructors
A default constructor is the constructor which doesn’t take any argument. It has no
parameter
Above program is an example of default constructor
Note :Even if we do not define any constructor explicitly ,the compiler will
automatically provide a default constructor implicitly. The default value of all data
members will be initialized to 0
Example:
Parameterized constructors
It is possible to pass arguments to constructors
Using this constructor you can provide different values to data members of different
objects
To create a parameterized constructor ,simply add parameters to it,similar to any other
functions
When you define the constructor’s body, use the parameters to initialise the object
#include<iostream>
using namespace std;
class cube
{
int length,volume;
public:
void volume()
{
volume=length*length*length;
cout<<”volume is “<<volume;
}
};
int main()
{
cube c;
c.volume();
return 0;
}
No constructor is
defined. So values
of dada members is
set to 0
OUTPUT
Volume is 0
KTUNOTES.IN
Downloaded from Ktunotes.in
Copy Constructors
These are special type of constructors which takes an object as
argument, and is used to copy values of data members of one object
into another object.
Destructors
Destructor is another special member function which destroys the object as soon
as the scope of the object ends
The destructor is automatically called by the compiler when the object goes out
of the scope
Syntax of destructor is same that of constructor,the class name is used as the
name of destructor , with a tilde ‘~’ sign as prefix to it
#include<iostream>
using namespace std;
class cube
{
int length,volume;
public:
cube(int n)
{
length=n;
}
void volume()
{
volume=length*length*length;
cout<<”\n volume is “<<volume;
}
};
int main()
{
cube c1(10);
cube c2(5);
cube c3(2);
c1.volume();
c2.volume();
c3.volume();
return 0;
}
Constructors
are called
with
arguments
OUTPUT
Volume is 1000
Volume is 125
Volume is 8
#include<iostream>
using namespace std;
class cube
{
public:
cube()
{ cout<<” \n constructor is called”;}
~cube()
{ cout<<” \n destructor is called”;}
};
int main()
{
cube c;
return 0;}
OUTPUT
constructor is called
destructor is called
Constructer get called when object is
created and destructor get called when
scope of the object ends
KTUNOTES.IN
Downloaded from Ktunotes.in
Inheritance
The capability of a class to derive properties and characteristics from another class is
called Inheritance . Inheritance is one of the most important feature of Object
Oriented Programming.Sub Class/Derived class: The class that inherits properties
from another class is called Sub class or Derived Class.Super Class/ Base class:The
class whose properties are inherited by sub class is called Base Class or Super class.
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be same for all of the three
classes. If we create these classes avoiding inheritance then we have to write all of these
functions in each of the three classes as shown in below figure:
You can clearly see that above process results in duplication of same code 3 times. This
increases the chances of error and data redundancy. To avoid this type of situation,
inheritance is used. If we create a class Vehicle and write these three functions in it and
inherit the rest of the classes from the vehicle class, then we can simply avoid the
duplication of data and increase re-usability. Look at the below diagram in which the
three classes are inherited from vehicle class:
Using inheritance, we have to write the functions only one time instead of three times
as we have inherited rest of the three classes from base class(Vehicle).
KTUNOTES.IN
Downloaded from Ktunotes.in
Implementing inheritance in C++:
For creating a sub-class which is inherited from the base class we have to follow the
syntax:
class subclassName : access_mode baseclassName
{
//body of subclass
};
Here, subclassName is the name of the sub class, access_mode is the mode in which you
want to inherit this sub class ,for example: public, private etc. and baseclassName is the
name of the base class from which you want to inherit the sub class.
Note: private member of the base class will never get inherited in the sub class.
In the above program the ‘area’ class is publicly inherited from the ‘rectangle’ class so
the public data members of the class ‘rectangle’ will also be inherited by the class
‘area’
Modes of Inheritance
Public mode: If we derive a sub class from a public base class. Then the public member
of the base class will become public in the derived class and protected members of the
base class will become protected in derived class. Private members of the base class will
never get inherited in sub class.
Protected mode: If we derive a sub class from a Protected base class. Then both public
member and protected members of the base class will become protected in derived class.
Private members of the base class will never get inherited in sub class.
#include<iostream>
using namespace std;
class rectangle
{
public:
int l,b;
void readdata()
{
cout<<"enter the length of rectangle: ";
cin>>l;
cout<<"enter the breadth of rectangle: ";
cin>>b;
}
};
class area:public rectangle
{
public:
void calc()
{
cout<<"area of rectangle is "<<l*b;
}
};
int main()
{
area a1;
a1.readdata();
a1.calc();
return 0;
}
Class area inherits from
class rectangle. Thus
area inherits l and b, and
function readdata()
Object of area is created, it
gets the function
readdata()
KTUNOTES.IN
Downloaded from Ktunotes.in
Private mode: If we derive a sub class from a Private base class. Then both public
member and protected members of the base class will become Private in derived class.
Private members of the base class will never get inherited in sub class.
The below table summarizes the above three modes and shows the access specifier of the
members of base class in the sub class when derived in public, protected and private
modes:
Types of Inheritance in C++
Single Inheritance: In single inheritance, a class is allowed to inherit from only one class.
i.e. one sub class is inherited by one base class only.
Syntax:
class subclassName : access_mode baseclass
{
//body of subclass
};
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle \n" <<;
}
};
class Car: public Vehicle
{
};
int main()
{
Car obj;
return 0;
}
creating object of
sub class wil invoke
the constructor of
base class
KTUNOTES.IN
Downloaded from Ktunotes.in
Output:
This is a vehicle
Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit
from more than one classes. i.e one sub class is inherited from more than one base
classes .
Syntax:
Class subclassName : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
Here, the number of base classes will be separated by a comma (‘, ‘) and access mode for
every base class must be specified.
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle \n" ;
}
};
class FourWheeler
{
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle \n" ;
}
};
class car: public Vehicle, public FourWheeler
{
};
int main()
{
car obj;
return 0;
}
Base class 1
Base class 2
sub class derived
from two base
classes
creating object of
sub class wil
invoke the
constructor of
base class
KTUNOTES.IN
Downloaded from Ktunotes.in
Output:
This is a Vehicle
This is a 4 wheeler Vehicle
Multilevel Inheritance: In this type of inheritance, a derived class is created from
another derived class
Output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
Output
This is a Vehicle
Objects with 4 wheels are vehicles
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
class fourWheeler: public Vehicle
{
public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles\n";
}
};
class Car: public fourWheeler
{
public:
Car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
int main()
{
Car obj;
return 0;
}
sub class
derived from
two base classes
Creating object of sub class
will invoke the constructor of
base classes
KTUNOTES.IN
Downloaded from Ktunotes.in
Hierarchical Inheritance: In this type of inheritance, more than one sub class is
inherited from a single base class. i.e. more than one derived class is created from a
single base class
Outout
This is a Vehicle
This is a Vehicle
Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more
than one type of inheritance. For example: Combining Hierarchical inheritance and
Multiple Inheritance. Below image shows the combination of hierarchical and multiple
inheritance
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle \n” ;
}
};
class Car: public Vehicle
{
};
class Bus: public Vehicle
{
};
int main()
{
Car obj1;
cout<<"\n \n";
Bus obj2;
return 0;
}
Sub class1
Sub class2
creating object
of sub class will
invoke the
constructor of
base classes
KTUNOTES.IN
Downloaded from Ktunotes.in
*******************************************************************
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle \n” ;
}
};
class f_wheeler
{
public:
f_wheeler()
{
cout << "it has 4 wheels \n” ;
}
};
class Car: public Vehicle, public f_wheeler
{
};
Class bike: public vehicle
{
};
Base class 1
Base class2
Multiple inheritance
Hierarchical inheritance:bike and car inherits
from class vehicle
KTUNOTES.IN
Downloaded from Ktunotes.in