5th Unit
5th Unit
Class sample
int m;
};
read();
Example:
#include<iostream>
class part
{
private:
int modelnum,partnum;
float cost;
public:
modelnum=mn;
partnum=pn;
cost=c;
void showpart()
cout<<endl<<"model:"<<modelnum<<endl;
cout<<"cost:$"<<cost;
};
main()
part p1,p2;
p1.setpart(644,73,217.55);
p2.setpart(567,89,789.55);
p1.showpart();
p2.showpart();
return 0;
OUTPUT:
model:644
num:73
cost:$217.55
model:567
num:89
cost:$789.55
POLYMORPHISM:
When an object is created from its class, the member variables and member
functions are allocated memory spaces. The memory spaces have unique
addresses. The pointer is a mechanism to access these memory locations
using their address rather than the name assigned to them. The pointer is a
variable which can hold the address of a memory location rather than the
value at the location. Consider the following statement
Compile-time Polymorphism
Runtime Polymorphism
1.Compile-time polymorphism: This type of polymorphism is achieved by
function overloading or operator overloading.
1.1 Function Overloading: When there are multiple functions with the same
name but different parameters then these functions are said to be
overloaded. Functions can be overloaded by a change in the number of
arguments or/and change in the type of arguments.
2.1.Function overriding on the other hand occurs when a derived class has a
definition for one of the member functions of the base class. That base
function is said to be overridden.
INHERITANCE :
Inheritance is one of the features of Object Oriented Programming
System(OOPs), it allows the child class to acquire the properties (the data
members) and functionality (the member functions) of the parent class.
What is child class?
A class that inherits another class is known as child class, it is also known as
derived class or subclass.
What is a parent class?
The class that is being inherited by another class is known as a parent class,
superclass or base class.
Advantages of inheritance:
Sometimes we need to repeat the code or repeat the class’s properties. So
inheritance helps in various ways :
1.It saves memory space.
2.It saves time.
3.It will remove frustration.
4.It increases reliability of the code
5. It saves developing and testing efforts.
TYPES OF INHERITANCE:
In C++, we have 5 different types of Inheritance. Namely,
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)
1.Single inheritance
In single inheritance, a class derives from one base class only. This means
that there is only one subclass that is derived from one superclass.
Single inheritance is usually declared as follows:
//class-specific code;
};
2.Multiple inheritance
Multiple inheritances is a type of inheritance in which a class derives from
more than one classes. As shown in the above diagram, class C is a subclass
that has class A and class B as its parent.
In a real-life scenario, a child inherits from its father and mother.
Diamond problem
Diamond Problem is pictorially represented below:
Here, we have a child class inheriting two classes Father and Mother. These
two classes, in turn, inherit the class Person.
As shown in the figure, class Child inherits the traits of class Person twice i.e.
once from Father and the second time from Mother. This gives rise to
ambiguity as the compiler fails to understand which way to go.
Since this scenario arises when we have a diamond-shaped inheritance, this
problem is famously called “The Diamond Problem”.
The Diamond problem implemented in C++ results in ambiguity error at
compilation. We can resolve this problem by making the root base class as
virtual.
3. Multilevel Inheritance
Multilevel inheritance is represented below.
In hierarchical inheritance, more than one class inherits from a single base
class as shown in the representation above. This gives it a structure of a
hierarchy.
Previous
TYPE CONVERSIONS:
In mixed expression constants and variables are of different data types. The
assignment operations cause automatic type conversion between the operand
as per certain rules.
The type of data to the right of an assignment operator is automatically
converted to the data type of the variable on the left.
Consider the following example:
int x;
float y = 20.123;
x=y ;
This converts float variable y to an integer before its value assigned to x. The
type conversion is
automatic as far as data types involved are built-in types. We can also use the
assignment operator in case of objects to copy values of all data members of
the right-hand object to the object on the left hand. The objects in this case
are of the same data type. But if objects are of different data types we must
apply conversion rules for assignment.
There are three types of situations that arise where data conversion is
between incompatible types.
1. Conversion from built-in type to class type.
2. Conversion from class type to built-in type.
3. Conversion from one class type to another.
Basic to Class Type
A constructor was used to build a matrix object from an int type array.
Similarly, we used another
constructor to build a string type object from a char* type variable. In these
examples, constructors performed a de facto type conversion from the
argument's type to the constructor's class type.
Consider the following constructor:
{
length = strlen (a);
name=new char[len+1];
strcpy (name,a);
This constructor builds a string type object from a char* type variable a. The
variables length and name are data members of the class string. Once you
define the constructor in the class string, it can be used for conversion from
char* type to string type.
Class to Basic Type
The constructor functions do not support conversion from a class to basic
type. C++ allows us to define an overloaded casting operator that converts a
class type data to basic type. The general form of an overloaded casting
operator function, also referred to as a conversion function, is:
operator typename ( )
//Program statement .
double sum = 0 ;
for(int i=0;i<5;i++)
return sqrt(sum);
}
return (str) ;
OPERATOR OVERLOADING:-
Operator overloading provides a flexible option for the creation of new
definitions for most of the C++ operators. We can overload all the C++
operators except the following:
• Class members access operator (. , .*)
• Scope resolution operator (: :)
• Size operator(sizeof)
• Condition operator (? :)
Although the semantics of an operator can be extended, we can't change its
syntax, the grammatical rules that govern its use such as the no of operands
precedence and associativity. For example, the multiplication operator will
enjoy higher precedence than the addition operator.
When an operator is overloaded, its original meaning is not lost.
For example,
the operator +, which has been overloaded to add two vectors, can still be
used to add two integers.
DEFINING OPERATOR OVERLOADING:
To define an additional task to an operator, we must specify what it means in
relation to the class to which the operator is applied. This is done with the help
of a special function
called the operator function, which describes the task.
Syntax:-
function body
Where return type is the type of value returned by the specified operation and
op is the operator being overloaded. The op is preceded by the keyword
operator, operator op is the function name.
operator functions must be either member function or friend function. A basic
difference between them is that a friend function will have only one argument
for unary operators and two for binary operators, This is because the object
used to invoke the member function is passed implicitly and therefore is
available for the member functions. Arguments may be either by value or by
reference.
Operator functions are declared in. the class using prototypes as follows:-
vector operator + (vector); // vector addition
vector operator-( ); //unary minus
friend vector operator + (vector, vector); // vector add
friend vector operator -(vector); // unary minus
vector operator - ( vector &a); // subtraction
int operator = =(vector); //comparison
friend int operator = =(vector ,vector); // comparison
A vector is a data type of class and may represent both magnitude and
direction or a series of points called elements.
The process of overloading involves the following steps:-
1. Create a class that defines the data type that is used in the overloading
operation.
2. Declare the operator function operator op() in the public part of the class
3. It may be either a member function or friend function.
4. Define the operator function to implement the required operations.
Overloaded operator functions can be invoked by expressions such as
op x or x op;
for unary operators and
x op y
for binary operators.
operator op(x);
for the unary operator using friend function
operator op(x,y);
for binary operators using friend functions.
Example –Unary Minus
#include<iostream>
class NUM
{ private:
int n;
void getNum(int x)
n=x;
void dispNum(void)
}
//unary - operator overloading
n=-n;
};
int main()
NUM num;
num.getNum(10);
num.dispNum();
~num;
num.dispNum();
return 0; }
Overloading an operator does not change its basic meaning. For example,
assume the +operator can be overloaded to subtract two objects. But the code
becomes unreachable.
class integer
int x, y;
public:
int operator +( ) ;
return (x-y) ;
}
CONSTRUCTORS:
A constructor is a special member function whose task is to initialize the
objects of its class. It is special because its name is the same as the class
name. The constructor is invoked whenever an object of its associated class is
created. It is called a constructor because it constructs the values of data
members of the class.
A constructor is declared and defined as follows:
class integ
int m,n;
public:
integ(void);//constructor declared
};
integer :: integer(void)
m=0;
n=0;
}
#include <iostream>
class A
public:
int a, b;
// Default Constructor
A()
a = 10;
b = 20;
};
int main()
A x;
cout << "a: " << x.a << endl << "b: " << x.b;
return 1;
OUTPUT:
a: 10
b: 20
2.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.
Uses of Parameterized constructor:
#include <iostream>
class P
private:
int x, y;
public:
// Parameterized Constructor
x = x1;
y = y1;
int getX()
return x;
int getY()
return y;
}
};
int main()
// Constructor called
P p1(10, 15);
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
OUTPUT:
p1.x=10, p1.y=15
3.Copy constructor
A copy constructor is a member function which initializes an object using
another object of the same class. A copy constructor has the following general
function prototype:
ClassName (const ClassName &old_obj);
In C++, a Copy Constructor may be called in the following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an
argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.
#include<iostream>
class P
private:
int x, y;
public:
{ x = x1;
y = y1;
// Copy constructor
P(const P &p2)
{x = p2.x;
y = p2.y; }
int getX()
{ return x; }
int getY()
{ return y; }
};
int main()
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
4.Dynamic Constructor:-
The constructors can also be used to allocate memory while creating objects.
This will enable the system to allocate the right amount of memory for each
object when the objects are not of the same size, thus resulting in the saving
of memory.
Allocation of memory to objects at the time of their construction is known as
dynamic constructors of objects. The memory is allocated with the help of a
new operator.
Example:-
#include<iostream>
class B {
const char* p;
public:
// default constructor
B()
{
// allocating memory at run time
p = new char[6];
p = "hello";
void display()
};
int main()
obj.display();
OUTPUT:
hello
class base
{
//Data Members
//Member Functions
};
//Data Members
//Member functions
};
void main ( ) {
derived obj ;
The pointer ptr points to an object of the derived class obj. But, a pointer to a
derived class object may not point to a base class object without explicit
casting.
For example, the following assignment statements are not valid
void main ( )
base obja;
derived *ptr;
}
A derived class pointer cannot point to base class objects. But, it is possible
by using explicit casting.
void main ( )
base obj ;
#include <iostream>
class item
int number;
float cost;
public:
cout<<"number:"<<number<<endl;
cout<<"cost :"<<cost<<endl;
};
{
number=a; cost=b;
main()
item x;
cout<<"\nobject x"<<endl;
x.getdata(100, 299.95);
x.putdata();
item y;
cout<<"\nobject y"<<endl;
y.getdata(200, 175.5);
y.putdata();
Output:
object x
number:100
Cost : 299.95
object y
number:200
Cost : 175.5
#include<iostream>
class marks
{
private:
int m1,m2;
public:
void getdata();
void displaydata();
};
void marks::getdata()
cin>>m1;
cin>>m2;}
void marks::displaydata()
int main(){
marks x; x.getdata();
x.displaydata();
return 0;}
OUTPUT:
class xyz
int x;
int y;
public:
int z;
};
xyz p;
p.z=10; ok ,z is public
function-body
The membership label class-name:: tells the compiler that the function
function - name belongs to the class class-name. That is the scope of the
function is restricted to the class- name specified in the header line. The::
symbol is called scope resolution operator.
Example:
number=a;
cost=b;
cout<<"number=:"<<number<<endl;
cout<<"cost="<<cost<<endl;
The member function has some special characteristics that are often used in
program development.
• Several different classes can use the same function name. The "membership
label" will resolve their scope, member functions can access the private data
of the class. A non-member function can't do so.
• A member function can call another member function directly, without using
the dot operator.
INSIDE THE CLASS DEFINITION:
Another method of defining a member function is to replace the function
declaration by the actual function definition inside the class.
Example:
class item
int number;
float cost;
public:
void putdata(void)
cout<<number<<endl;
cout<<cost<<endl;
};
DESTRUCTOR:-
A destructor, us the name implies is used to destroy the objects that have
been created by a
constructor. Like a constructor, the destructor is a member function whose
name is the same as the class name but is preceded by a tilde.
For Example:-
~ integer( )
{}
A destructor never takes any argument nor does it return any value. It will be
invoked implicitly
by the compiler upon exit from the program to clean up storage that is no
longer accessible. It is a good
practice to declare destructor in a program since it releases memory space for
future use.
Delete is used to free memory which is created by new.
Example:-
matrix : : ~ matrix( )
{
for(int i=0; i<11;i++)
delete p[i];
delete p;
}
#include<iostream>
class demo
int x;
int y;
public: demo()
x=0;
y=0;
cout<<"Object created\n";
demo(int a)
{ x=a;
cout<<"Object created\n";
demo(int a,int b)
{
x=a;
y=b;
cout<<"Object created\n"; }
void display(void)
cout<<x<<"\n";
cout<<y;
cout<<"\n===============\n";
x=f.x;
y=f.y;
cout<<"Object created\n";
~demo()
cout<<"Object destroyed\n";
}};
int main()
demo d;
demo d1=demo(4);
demo d2(5,6);
demo d4(d2);
demo d5;
d.display();
d1.display();
d2.display();
d4.display();
return 0;}
OUTPUT:
Object created
Object created
Object created
Object created
object created
==============
==============
==============
==============
Object destroyed
Object destroyed
Object destroyed
Object destroyed
Object destroyed
#include<iostream>
class employee
private:
char name[20];
public:
void getdata();
void putdata();
};
void employee::getdata()
cin>>name;
cin>>age;
cout<<"enter salary:"<<endl;
cin>>sal;
cout<<name <<endl;
cout<<age<<endl;
cout<<sal<<endl;
int main()
int i;
employee emp[5];
emp[i].getdata();
cout<<"\n";
cout<<endl;
for(i=0;i<2;i++)
emp[i].putdata();
cout<<"\n";
return 0;
OUTPUT:
enter name :
abc
enter age :
23
enter salary;
10000
enter name :
xyz
enter age :
34
enter salary;
15000
abc
23
10000
xyz
34
15000
ARRAY OF OBJECTS:
#include<iostream>
class emp
{
private:
char name[20];
int age,sal;
public:
void getdata( );
void putdata( );
};
cout<<"enter empname:"<<endl;
cin>>name;
cout<<"enter age:"<<endl;
cin>>age;
cin>>sal;
cout<<"emp name:"<<name<<endl;
cout<<"emp age:"<<age<<endl;
cout<<"emp salary:"<<sal<<endl;
main()
int i;
emp foreman[5];
emp engineer[5];
for(int i=0;i<2;i++)
{
cout<<endl;
foreman[i].getdata();
cout<<endl;
for(i=0;i<2;i++)
foreman[i].putdata();
for(int i=0;i<2;i++)
cout<<endl;
engineer[i].getdata();
cout<<endl;
for(i=0;i<2;i++)
engineer[i].putdata();
return 0;
OUTPUT:
for foreman:
enter empname:
abc
enter age:
23
enter salary :
1234
for foreman:
enter empname:
xyz
enter age:
12
enter salary :
1233
emp name:abc
emp age:23
emp salary:1234
emp name:xyz
emp age:12
emp salary:1233
for engineer:
enter empname:
ert
enter age:
34
enter salary :
3456
for engineer:
enter empname:
frt
enter age:
45
enter salary :
5678
emp name:ert
emp age:34
emp salary:3456
emp name:frt
emp age:45
emp salary:5678
#include <iostream.h>
class set
int m,n;
public:
void input(void);
void display(void);
void largest(void);
};
int set::largest(void)
if(m>n)
return m;
else
return n;
void set::input(void)
cin>>m>>n;
void set::display(void)
cout<<"largest value="<<largest()<<"\n";
void main()
set A;
A.input();
A.display();
output:
largest value= 30
Pointers in C++:
An object of a class behaves identically as any other variable. Just as pointers
can be defined in case of base C++ variables so also pointers can be defined
for an object type. To create a pointer variable for the following class:
class employee {
int code;
public:
};
class ABC
int a ;
};
The private variable ‘a’ can be used directly inside a member function, like
a=123;
We can also use the following statement to do the same job.
this → a = 123
e.g.
class stud
{
int a;
public:
void show ( )
cout << a;
};
main ( )
S1.bet (5) ;
S2.show ( );
o/p = 5
Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in the base class.
The resolving of a function call is done at Run-time.
POINTER TO MEMBERS:
It is possible to take the address of a member of a class and assign it to a
pointer. The address
of a member can be obtained by applying the operator & to a “fully qualified”
class member name.
A class member pointer can be declared using the operator:: * with the class
name.
For Example:
class A
private:
int m;
public:
void show( );
};
#include<iostream.h>
class time
int hours;
int minutes;
public:
hours=h;
minutes=m;
void puttime(void)
cout<<minutes<<"minutes:"<<end;
};
minutes=t1.minutes + t2.minutes;
hours=minutes%60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
int main()
time T1,T2,T3;
T1.gettime(2,45);
T2.gettime(3,30);
T3.sum(T1,T2);
cout<<"T1=";
T1.puttime();
cout<<"T2=";
T2.puttime();
cout<<"T3=";
T3.puttime();
return 0;
FRIENDLY FUNCTIONS:-
We know private members can not be accessed from outside the class. That
is a non - member
function can't have an access to the private data of a class. However, there
could be a case where two classes manager and scientist have been defined.
We should like to use a function income- tax to operate on the objects of both
these classes.
In such situations, c++ allows the common function to be made friendly with
both the classes, thereby following the function to have access to the private
data of these classes.Such a function need not be a member of any of these
classes.
To make an outside function "friendly" to a class, we have to simply declare
this function as a friend of the classes as shown below :
class ABC
public:
};
#include<iostream>
class myclass
int a,b;
public:
myclass(int x,int y)
{
a=x;
b=y;
};
int sum(myclass m)
return m.a+m.b ;
main()
myclass my(10,20);
cout<<sum(my);
return 0;
OUTPUT:
30
#include<iostream.h>
class item
int number;
public:
void getdata(int a)
number=a;
count++;
void getcount(void)
cout<<"count:";
cout<<count<<endl;
};
int main( )
item a,b,c;
a.getcount( );
b.getcount( );
c.getcount( ):
a.getdata( ):
b.getdata( );
c.getdata( );
a.getcount( );
b.getcount( );
c.getcount( );
return 0;
count:0
count:0
count:0
count:3
count:3
count:3
Explanation:
The static variable count is initialized to Zero when the objects created. The
count is incremented whenever the data is read into an object. Since the data
is read into objects three times the variable count is incremented three times.
Because there is only one copy of count shared by all the three objects, all the
three output statements cause the value 3 to be displayed.
STATIC MEMBER FUNCTIONS:-
A member function that is declared static has the following properties:-
1. A static function can have access to only other static members declared in
the same class.
2. A static member function can be called using the class name as follows:-
class - name :: function - name;
Example:-
#include<iostream.h>
class test
int code;
public:
void set(void)
code=++count;
void showcode(void)
{ cout<<"count="<<count<<endl; }
};
int main()
test t1,t2;
t1.setcode();
t2.setcode();
test :: showcount();
test t3;
t3.setcode();
test:: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
output:-
count: 2
count: 3
object number 1
object number 2
object number 3
CLASS:-
Class is a group of objects that share common properties and relationships. In
C++, a class is a new data type that contains member variables and member
functions that operates on the variables. A class is defined with the keyword
class. It allows the data to be hidden, if necessary from external use. When
we define a class, we are creating a new abstract data type that can be
treated like any other built-in data type.
Generally, a class specification has two parts:-
a) Class declaration
b) Class function definition
The class declaration describes the type and scope of its members. The class
function definition describes how the class functions are implemented.
Syntax:-
class class-name
{
private:
variable declarations;
function declaration ;
public:
variable declarations;
function declaration;
};
The members that have been declared as private can be accessed only from
within the class. On the other hand, public members can be accessed from
outside the class also. The data hiding is the key feature of
oops. The use of keywords private is optional by default, the members of a
class are private.
The variables declared inside the class are known as data members and the
functions are known as members mid the functions.
Only the member functions can have access to private data members and
private functions.
However, the public members can be accessed from outside the class. The
binding of data and functions together into a single class type variable is
referred to as encapsulation.
Syntax:-
class item
int member;
float cost;
public:
void putdata(void);
}
The class item contains two data members and two function members, the
data members are private by default while both the functions are public by
declaration.
The function getdata() can be used to assign values to the member variables
member and cost, and putdata() for displaying their values.
These functions provide the only access to the data members from outside the
class.
CREATING OBJECTS:
Once a class has been declared we can create variables of that type by using
the class name.
Example:
item x;
creates a variable x of type item. In C++, the class variables are known as
objects. Therefore x is called an object of type item.
item x, y,z also possible.
class item
{
}x ,y ,z;
would create the objects x ,y ,z of type item.