Unit-3 CC
Unit-3 CC
COM IT
COURSE CONTENT
CLASS:II B.COM IT
Syllabus
Unit - III
class class_name
{
private:
variable declaration;
public:
function declaration;
…
};
• The body of the declaration can contain members that can be either data or
function declaration, and optionally access specifier.
• The variable declared inside the class is known as data member and function
are known as member functions.
• Access specifier are keyword in object oriented language that set the
accessibility of classes, method and other member.
• Access specifier is one of the following keyword: public, private, protected
• These specifier modify the access rights that the member following
• them acquire:
o private members of class are accessible only from within other member
of same class or from their friends.
o protected members are accessible form members of their same class
and from their friends but also from members of their derived classes.
o public members are accessible from anywhere the object is visible.
• By default, all members of class declared with the class keyword have private
access for all its member. Therefore, any member that is declared before one
other class specifier automatically has private access.
• Only member function can have access to private data member and private
function of that data.
OBJECT:
• Once a class has been created, we can create variable of that type(class type)
by using following syntax which is called object.
• we can create any number of objects belonging to that class by declaring more
than one object in one statement. This statement are written in main().
• The objects can also be defined by placing their name immediately after the
closing brace of the class.
Syntax:
object_name.member_function(arguments);
Ex:
s.getdata();
• A data member can also be access by using object only , if data member is
declared as public.
• If data member is declared private then you cannot access it by using object
directly in object
return_type
class_name::function_name(arument)
{
function body
}
• The membership label class_name :: tells the compiler that the function
function_Name belongs to the class class_name.
• :: is scope resolution operator.
• We can define a member function outside and still make it inline by just using the
qualifier inline in the header line of function definition.
Nesting Member Function:
• A member function can be called by using its name inside another member
function the same class is called nesting member function.
• Ex:
#include<iostream>
using namespace std;
class number
{
private:
int a,b,s1,s2;
public:
int getdata(int m,int n);
int sum();
int sub();
int show()
{
cout<<"\n Enter number1: ";
cin>>a;
cout<<"\n Enter number2: "; cin>>b;
cout<<"\n Answer of Addition:"<<sum()<<endl; cout<<"\n Answer of
Addition:"<<sub()<<endl;
}
};
int number::getdata(int m,int n)
{
a=m; b=n;
}
int number::sum()
{
s1=a+b; return(s1);
}
int number :: sub()
{
s2=a-b; return(s2);
}
int main()
{
number x; x.getdata(10,20); x.show();
return 0;
}
• Ex:
#include<iostream>
using namespace std;
class average
{
private:
int n,A[20];
public:
void getdata()
{
cout<<"Number of element: "; cin>>n;
cout<<"Enter the data in array:\n "; for(int i=0;i<n;i++)
{
cout<<"A["<<i<<"]";
cin>>A[i];
}
}
float avg()
{
float sum=0,ans; for(int i=0;i<n;i++) sum=sum+A[i]; ans=sum/n;
cout<<"Average is: "<<ans;
}
};
int main()
{
average a; a.getdata();
a.avg();
return 0;
Memory allocation for object:
• The memory space for objects are allocated when they are declared , not when
the class is specified.
• For member function , when member function are created it will occupy the
memory space only once when they are defining in a class.
• So all objects created for that class can use same member functions , so no
separate space is allocated for member functions when the object are created.
• For data member , only space for data members is allocated separately for each
object when is created.
• The separate space allocation for data member is essential because the data
member will hold different data values for different objects.
• For example, a class student have three data members such as reg_no, age,
per and two member functions getdata() and show().
• If we create three object S1 ,S2, S3 then, object S1 takes up space for: reg_no ,
age , per object S2 takes up space for: reg_no , age , per object S3 takes up
space for: reg_no , age , per
• But it will access common member function getdata() and show(), so it will take
up space only one time when class is created.
Returning objects:
• A function can not only receive objects as arguments but also can return them.
• Like:
#include<iostream>
using namespace std;
class SUM
{
int x;
public:
void getdata(int m)
{
x=m;
}
SUM sum(SUM s)
{
SUM temp;
temp.x=x+s.x;
return(temp);
}
void show()
{
cout<<"Answer is: "<<x;
}
};
int main()
{
SUM s1 ,s2,s3;
s1.getdata(4);
s2.getdata(10);
s3=s1.sum(s2);
s3.show();
return 0;
}
Friendly Functions:
• Due to ‘data hiding ’ feature of c++, the private data members of class can not
be access outside the class. So a function which are not member of the class,
they can not be access the private data of that class.
• In c++, there is facility available to access private data of class even if it is not
member function of that class. It is possible bye using friend function.
• As the name suggests, the function acts as a friend to a class. As a friend of a
class, it can access its private and protected members.
• To make an outside function “friendly” to class, declare the function as friend of
that class.
• The friend functions are declared by using friend keyword.
Syntax:
friend return_type function_name(arg_list);
• Generally arguments in friend functions are object type. because of outside the
class a data member can not directly access, so a object can access it.
• A function can be declared as friend for any number of class. It can not be
member function of any class. It have full rights to access private data of the
class.
• Advantage of having friend function:
1. We can able to access the other class members in our class, if we use
friend keyword.
2. We can access the members without inheriting the class.
• Disadvantage:
1. Maximum size of memory will occupied by object
according to the size of friend member.
2. Break the concept of ‘data hiding’ in oop.
• Characteristic of friend function:
1. It is not in the scope of the class which it has been declared as friend.
2. It can not be called using the object of that class. It can be invoked like a
normal function without the help of object.
3. It can not access data member directly, it must be use object with dot(.)
operator and data member.
4. Normally it has object as argument.
• Ex:
#include<iostream>
using namespace std;
class MEAN{ int n1,n2; public:
void getdata()
{
cout<<"Enter num1: "; cin>>n1; cout<<"Enter num2: "; cin>>n2;
}
friend float ans(MEAN m);
};
float ans(MEAN m)
{
return float(m.n1+m.n2)/2;
}
int main()
{
MEAN m1;
m1.getdata();
cout<<"Answer is: "<<ans(m1); return 0;
}
• Function member can made constant by writing word const keyword between
header of the function and body.
• Normally function member which are not supposed to modify the object should
be made constant so that there are no chance that accidently function member
modifies the object.
Pointer to Member:
• Just like pointer to normal variable and function , we can have pointer to class
member function and member variable.
syntax: • Ex:
data_type class_name::*pointer_name=&class_name::data_member int A::*p=&A::m;
• Pointer to member functions are one of the c++’s rarely used features, while
they do not have widely applicability, some time member function pointer are
useful to solve certain problems.
• Member function pointer can not be dereferenced directly by themselves .they
must be called on behalf of some object.
• To declare a pointer to member function you give the prototype of function it can
point to,as before but the name of this function is replaced by a construction that
scopes the pointer – you give it the name of the class whose member function it
can point to.
Syntax:
return_type (class_name::*pointer_name)(argument_list)
• You dereference a member function pointer by using .* or ->*, supplying a
reference or pointer to an object on the left, as appropriate , and the function
pointer on the right.
• Note that member function does not have the same data type as nonmember
function that has the same number and type of argument and the same return
type.
• Ex.
#include<iostream> using namespace std;
class test{ public: int a;
void fun(int b)
{
cout<<"The value of b is: "<<b<<endl;
}
};
int main()
{
int test::*p=&test::a; // pointer to data member declaration
void(test::*p1)(int)=&test::fun; // pointer to function declaration
test T;
T.*p=10;
cout<<"The value of a is:"<<T.*p<<endl; (T.*p1)(20);
}
student
{
}
Characteristic of constructor:
• In above program, we have written default constructor that is exactly same as the
compiler provide.
• We can write initialization statement in body part of default constructor which is
allowed.
• For that constructor first create the object by allocating memory and then execute
statements in body of constructor, if provided.
• If we provide the initialization statements in body of constructor, the object gets
initialized by default values provided in body at the time of creating object as
constructor.
• for Ex:
point() // default constructor with initialization
{
X=0; Y=0;
}
Parameterized constructor:
• The default constructor are used initialize the object with default values.
• But all objects are not initialized to same values rather different object needs
to be initialized by different values.
• To initialize object with different values, we use function like getvalue().
• C++ provides feature is parameterize constructor to solve this problem.
• The constructor that can take arguments are called parameterize
constructor .
• The advantage of using parameterize constructor that we can pass the
value at the time of defining object with which the compiler automatically calls
it
• Ex
#include<iostream>
using namespace std;
class point
{
int x,y;
public:
point() //default constructor
{
x=0; y=0;
}
point(int x1,int y1) //parameterized constructor
{
x=x1; y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(3,9); cout<<"point P1 is = "; p1.put_point(); cout<<"point P2 is =
"; p2.put_point();
return 0;
}
Multiple Constructor: (Overloaded Constructor)
• In a class if we use more than one constructor with each constructor are
different, this concept is called constructor overloading.
• Ex:
#include<iostream>
using namespace std;
class point
{
int x,y;
public:
point() //default constructor
{
x=0; y=0;
}
point(int x1) //one parameter constructor
{
x=x1; y=0;
}
point(int x1,int y1) //two parameter constructor
{
x=x1; y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(3),p3(3,4);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
cout<<"point P3 is = ";
p3.put_point();
return 0;
}
Constructor with Default Argument:
{
x=x1; y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2,p3;
cout<<"Enter x1 co-ordinate:";
int m,n;
cin>>m;
cout<<"Enter y1 co-ordinate:";
cin>>n;
p1=point(m,n);
cout<<"Enter x2 co-ordinate:";
cin>>m;
cout<<"Enter y2 co-ordinate:";
cin>>n;
p2=point(m,n);
cout<<"Enter x3 co-ordinate:";
cin>>m;
cout<<"Enter y3 co-ordinate:";
cin>>n;
p3=point(m,n);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
cout<<"point P3 is = ";
p3.put_point();
return 0;
}
Copy Constructor:
Syntax
class_name(class_name& object)
{
// constructor body
}
• For ex:
point(point& p) //copy constructor
{
x=p.x;
Y=p.y;
}
• Observe that constructor has one argument which is reference to the object
of same class of which the copy constructor is member. Using this reference,
it copies each data member.
• We can call copy constructor in either ways
point p2(p1);
or
point p2=p1;
• Ex
#include<iostream>
using namespace std;
class point{ int x,y; public: point()
{
x=0; y=0;
}
point(int x1,int y1)
{
x=x1; y=y1;
}
point(point& p)
{
x=p.x;
y=p.y;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(1,1);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
point p3(p2);
cout<<"point P3 is = ";
p3.put_point();
point p4(p1);
cout<<"point P4 is = ";
p4.put_point();
return 0;
}
Dynamic Constructor:
• The constructor can also be used to allocate memory while creating objects.
• This will enable the system to allocate the right amount of memory for each
objects when the objects are not of the same size, thus resulting is the
saving memory.
• Allocation of memory to object at the time of their constructor is called
dynamic constructor.
• The memory is allocated with help of new operator.
• By using new operator we get exact amount of memory storage space at run
time which are used in constructor.
• Ex
#include<iostream> #include<string.h>
using namespace std; class String
{
char *name; int length; public:
String()
{
length=0;
name= new char[length+1];
}
String(char *s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
void display()
{
cout<<name<<"\n";
}
};
int main()
{
char *str="Welcome";
String str1(str),str2("BCA");
String str3(str),str4;
str1.display();
str2.display();
str3.display();
return 0;
}
#include<iostream>
using namespace std; class matrix
{
int **p; int d1,d2; public:
matrix(int x,int y);
void get_element(int i,int j,int val)
{
p[i][j]=val;
}
int &put_element(int i,int j)
{
return p[i][j];
}
};
matrix:: matrix(int x, int y)
{
d1=x; d2=y;
p= new int *[d1];
for(int i=0;i<d1;i++)
{
p[i]=new int[d2];
}
}
int main()
{
int m,n;
cout<<"Enter size of matrix: "; cin>>m>>n;
matrix A(m,n);
cout<<"Enter matrix Element: "; int i,j,val;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>val; A.get_element(i,j,val);
}
cout<<"\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<" "<<A.put_element(i,j)<<" ";
}
cout<<"\n";
}
cout<<"\n";
cout<<"The value of on position(1,2) is : "<<A.put_element(1,2); cout<<"\n";
return 0;
}
Const Object:
• We may create and use constant object using const keyword before
object declaration.
• For Ex:
const matrix X(m,n);// X is constant
• Any attempt to modify the value of const object will generate compile-time
error.
• A constant object can call only const member function.
Destructors:
Characteristics of Destructor:
• A destructor never takes any arguments and does not return any value.
• Destructor is having same name as class preceded by tild(~) sign.
• It is called automatically when the scope of object is over.
• Default destructor is provided by compiler, if user does not
• provide.
• Ex:
Operator Overloading
• Operator overloading is an important concept in C++. It is a type of
polymorphism in which an operator is overloaded to give user defined
meaning to it. Overloaded operator is used to perform operation on user-
defined data type. For example '+' operator can be overloaded to perform
addition on various data types, like for Integer, String(concatenation) etc.
• Almost any operator can be overloaded in C++. However there are few
operator which cannot be overloaded. Operator that are not
overloaded are follows
scope operator - ::
sizeof
member selector - .
member pointer selector - *
ternary operator - ?:
1. Member Function
2. Non-Member Function
3. Friend Function
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Output:
12 + i9
• The unary operators operate on a single operand and following are the
examples of Unary operators −
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
• The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -obj, and
++obj but sometime they can be used as postfix as well like obj++ or obj--.
• Following example explain how minus (-) operator can be overloaded for prefix
as well as postfix usage.
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
int main() {
Distance D1(11, 10), D2(-5, 11);
-D1; // apply negation
D1.displayDistance(); // display D1
return 0;
}
Output
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11
• The binary operators take two arguments and following are the examples of
Binary operators. You use binary operators very frequently like addition (+)
operator, subtraction (-) operator and division (/) operator.
• Following example explains how addition (+) operator can be overloaded.
Similar way, you can overload subtraction (-) and division (/) operators.
#include <iostream>
using namespace std;
class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
double getVolume(void) {
return length * breadth * height;
}
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
Output
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Type Conversion
• Type conversion is the process of converting one type into another. In
other words, converting an expression of a given type into another is
called as Type casting.
• There are two ways of achieving the type conversion namely,
Automatic Conversions otherwise called as Implicit
Conversions
Type Casting otherwise called as Explicit Conversions
Implicit Conversions:
Done by the compiler on its own, without any external trigger from the
user.
Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to
avoid lose of data.
All the data types of the variables are upgraded to the data type of the
variable with largest data type.
bool -> char -> short int -> int ->
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
return 0;
}
Output:
x = 107
y=a
z = 108
Explicit Conversions:
• This process is also called type casting and it is user-defined. Here the
user can typecast the result to make it of a particular data type.
• In C++, it can be done by two ways:
1. .Converting by assignment: This is done by explicitly defining the
required type in front of the expression in parenthesis. This can be
also considered as forceful casting.
Syntax
(type) expression
here type indicates the data type to which the final
result is converted.
• Example:
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
return 0;
}
Output:
Sum = 2
cout << b;
}
Output:
3
POSSIBLE 5 MARKS
1. Explain the concept of copy constructor with the help of an example program .
[Dec 2012]
2. What is operator overloading ? Briefly explain general rules of operator overloading.
[June 2013]
3. What do you mean by copy constructor ? Explain it with a suitable C++ program. [June
2014]
4. Differentiate between default constructor and parameterized constructor with the help of
an example [June 2015]
5. List the C++ operators that cannot be overloaded. Give reasons for any two of these
explaining why they cannot be overloaded.[June 2016]
6. What do you understand by a Default Constructor ? How is a default constructor
equivalent to a constructor with default arguments ? [ Dec 2017]
POSSIBLE 8 MARKS
1. Write a program in C++, which take two 10 3 x 3 matrices as input and find sum of
them. Implement suitable constructor and destructor for this program. [Dec 2012]
2. Explain need of operator overloading. Also explain why some operators cannot
be overloaded ? Write a C++ program to overload '+' operator to add two
character strings. [Dec 2012]
3. Write C++ program to find factorial of a given number using copy constructor.
[ Dec 2014]
4. What do you mean by operator-overloading ? List the operators which cannot be
overloaded. Write a C++ program for unary minus (-) operator overloading.[June
2015]
5. Write a C++ program to add two complex numbers. In this program you need to
create complex class and define proper constructor for object initialization. [ June
2015]
6. Write a C++ program to create a matrix class. Define constructor and destructor
for this class. Also define a method to find the sum of two matrices. [June 2017]
7. What is the difference between overloading and overriding concepts in C++ ?
Explain the usage of these concepts with suitable example code in C++. [Dec
2017]
8. Write a C++ program to create a Book class. Define constructor and destructor
for this class. Also define the methods to show the title and price of the books.
[Dec 2016]