UNIT-2
Class Definition
Class : A class is an abstract data type is to bind the data and its associated functions together. It
can also hide the data and functions if required.
A class specification consists of two parts.
1 : class declaration.
2 : class function definitions.
1 : class declaration : The syntax of a class declaration is :
class classname
{
private :
variable declaration;
function declaration;
public :
variable declaration;
function declaration;
};
1 : The class declaration is similar to a ‘C’ struct declaration.
2 : The class keyword indicates an abstract data type called name of the class.
3 : The body of a class is enclosed within braces and teriminated by a semicolon.
4 : The class body contains the declaration of variables and functions. These functions and
variables are collectively called class members.
5 : They are usually grouped under two sections, namely private and public. The keywords
private
and public are known as visibility labels. These keywords are followed by a colon.
6 : The class members that have been declared as private can be accessed only from within the
class.
7 : The class members that have been declared as public can be accessed from outside the class.
8 : The use of the keyword private is optional. By default the members of a class are private. If
both the labels are missing, then by default, all the members are private. Such a class is
completely hidden from the outside world and does not serve any purpose.
9 :The variables declared inside the class are known as data members and the functions are
known as member functions. Only the member functions can be accessed private data and
private
functions. Public member function ( both data and member functions ) can be accessed from
outside the class.
Creating Objects : once a class has been declared, we can create variables of that type by
using the class name.
Synata : classname object;
Ex : sample s;
Creates a variable s of type sample. In c++ the class variables are known as objects. S is called
an
object of type sample.
we may also declare morethan one object in one statement.
Synatax : classname object1,object2….objectN.
Ex : sample s,s1,s2;
How to Access Member Function : member function can be accessed ofter a class is defined
and
objects are created.
Synatax : [Link];
[Link]();
The dot(.) is called the dot operator or class member acess operator. The dot
operator
is used to connect the object and the member function.
2 : A class Member Functions : member functions can be defined in two types.
1 : Inside the class definition.
2 : Outside the class definition.
1 : Inside the class definition : All the member functions defined within the body of a class.
Ex : date class which member function defined inside a class
#include<iostream.h>
class date
{
int day,month,year;
public :
void getdata(int day1,int month1,int year1)
{
day=day1;
month=month1;
year=year1;
}
void display()
{
cout<<day<<"-"<<month<<"-"<<year<<endl;
}
};
int main()
{
date d1,d2,d3;
[Link](2,6,1990);
[Link](3,7,1991);
[Link](4,8,1992);
cout<<"Date of birth first author:";
[Link]();
cout<<"date of birth second author:";
[Link]();
cout<<"date of birth third author:";
[Link]();
getch();
return 0;
}
2 :Outside the class definition : A member function that are declared within the body of a class
have to defined separately outside the class. Their definitions are very much like normal
function.
They should have a function body and function body.
Syntax : returntype classname :: functionname(arguments)
{
// function body;
}
Ex : outside the class definition
#include<iostream.h>
#include<conio.h>
class item
{
int number;
float cost;
public :
void putdata(int x,float y);
void display();
};
void item :: putdata(int x, float y)
{
number=x;
cost=y;
}
void item::display()
{
cout<<"number is:"<<number<<endl;
cout<<"cost is :"<<cost;
}
int main()
{
item x1;
clrscr();
[Link](10,12.35);
[Link]();
getch();
return 0;
}
Nested Member Function : A member function can be called by using its name inside another
member function of the same class. This is known as nesting of member functions.
Ex
#include<iostream.h>
class sample
{
int m,n;
public :
void input();
int read();
void display();
};
int sample :: read()
{
if(m>=n)
return(m);
else
return(n);
}
void sample :: input()
{
cout<<"Enter m and n values";
cin>>m>>n;
}
void sample :: display()
{
cout<<"largest value is:"<<read();
}
int main()
{
sample s;
[Link]();
[Link]();
return 0;
}
Private Member Function : A private member function can only be called by another function
that is a member of its class. Even an object cannot invoke a private function using the dot
operator.
Ex :
//Private Member Function
#include<iostream.h>
#include<conio.h>
class sample
{
int m,n;
int read()
{
if(m>=n)
return(m);
else
return(n);
}
public :
void input();
void display();
};
void sample :: input()
{
cout<<"Enter m and n values";
cin>>m>>n;
}
void sample :: display()
{
cout<<"largest value is:"<<read();
}
int main()
{
sample s;
clrscr();
[Link]();
[Link]();
getch();
return 0;
}
Parameter passing methods : Two ways of parameter passing methods.
1 : call by value.
2 : call by reference.
1 : Call by value : When a function is called with actual parameters, the values of actual
parameters are copied into formal parameters. If the values of the formal parametes changes in
the
function, the values of the actual parameters are not changed. This way of passing parameters is
called call by value.
Ex : #include<iostream.h>
class sample
{
public :
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
};
void main()
{
sample s;
int i,j;
cout<<"enter i and j values:";
cin>>i>>j;
cout<<"before swapping:"<<i<<" "<<j<<endl;
[Link](i,j);
cout<<"after swapping:"<<i<<" "<<j<<endl;
}
2 : Call by reference : In pass by reference, a function is called with addresses of actual
parameters. In the function header, the formal parameters receive the addresses of actual
parameters. Now the formal parameters do not contain values, instead they contain addresses.
Any variable if it contains an address, it is called a pointer variable. Using pointer variables, the
values of the actual parameters can be changed. This way of passing parameters is called call by
reference or pass by reference.
Ex :
#include<iostream.h>
#include<conio.h>
class sample
{
public :
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
};
int main()
{
int i,j;
clrscr();
sample s;
cout<<"enter i and j value:";
cin>>i>>j;
cout<<"before swapping:"<<i<<" "<<j<<endl;
[Link](&i,&j);
cout<<"after swapping:"<<i<<" "<<j<<endl;
getch();
return 0;
}
Inline Function : An inline function is a function that is expanded in line when it is invoked.
The C++ compiler replaces the function call with the corresponding function code. Afunction
can
be made inline by using the keyword inline.
Syntax : inline function_name(arguments)
{
// body of the function;
}
The function declaration should be preceded by the keyword inline. All inline
functions must be defined before they are called.
Some situation inline function may not work :
1 : Function returning values, if a loop, a switch, or a goto exists.
2 : Functions with a return statement but not returning any value.
3 : Functions contain static variables.
4 : inline functions are recursive.
Advantages of Inline Function :
1: The size of the object code is reduced.
2 : it increase the execution speed.
3 : The Inline member functions are compact function calls.
Disadvantages of Inline Function : it is useful only for small functions.
#include<iostream.h>
#include<conio.h>
class sample
{
int x,y;
public :
inline void getdata();
inline void display();
inline int sum();
inline int mul();
inline int diff();
inline int div();
};
inline void sample :: getdata()
{
cout<<"Enter x and y values:"<<endl;
cin>>x>>y;
}
inline void sample :: display()
{
cout<<"x value is:"<<x<<endl;
cout<<"y value is:"<<y<<endl;
}
inline int sample :: sum()
{
return(x+y);
}
inline int sample :: diff()
{
return(x-y);
}
inline int sample :: mul()
{
return(x*y);
}
inline int sample :: div()
{
return(x/y);
}
int main()
{
clrscr();
sample s;
[Link]();
[Link]();
cout<<"sum is:"<<[Link]()<<endl;
cout<<"diff is:"<<[Link]()<<endl;
cout<<"mul is:"<<[Link]()<<endl;
cout<<"div is:"<<[Link]()<<endl;
getch();
return 0;
}
Static class members : A class member declared with the keyword static is called as static
class member. Static class members can be classified into two types.
Static class
members
Staic data Static member
members functions
Static Data Members : The static member variable is similar to C static variable. Static
member
variable allows a common value to be used for the entire class. The properties of static variables
are
1 : static variable is initialized to zero when the first object of its class is created.
2 : single copy of its shared among all the objects.
3 : It is visiable only within the class, but its lifetime is the entire program.
Static variables are normally used to maintain values common to the entire class.
Note : returntype classname :: static variable; // definition of static data member.
The type and scope of each “static” member variable must be defined outside the class.
Because the static data member are stored separately ratherthan as a part of an object.
#include<iostream.h>
class item
{
static int count;
int number;
public :
void getdata(int a)
{
number=a;
count++;
cout<<"count is :"<<count<<"\n";
}
void getcount()
{
cout<<"count is :"<<count<<"\n";
}
};
int item :: count; // definition of static data member
int main()
{
item a,b,c;
[Link]();
[Link]();
[Link]();
[Link](100);
[Link](200);
[Link](300);
cout<<"after reading"<<"\n";
[Link]();
[Link]();
[Link]();
return 0;
}
Staic Member Function : A static member function is declared using the keyword static has the
following characterstics.
1 : A static function can acess only the static members of its class.
2 : A static member function can be called using the classname.
Syntax : classname :: functionname;
//Static Member Function
#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public :
void setcode()
{
code=++count;
}
void showcode()
{
cout<<"object number is :"<<code<<"\n";
}
static void showcount()
{
cout<<"count is :"<<count<<"\n";
}
};
int test :: count; //definition of static data member
int main()
{
test t1,t2;
clrscr();
[Link]();
[Link]();
test :: showcount(); // static member function
[Link]();
[Link]();
getch();
return 0;
}
Acess Specifiers (Or) Acess Control : The acess specifier is a keyword that specifies how to
acess the members of a class. In C++ supports 3 types Acess specifiers.
1 : private
2 : public
3 : protected
1: private : if a class members that have been declared as a private, it can be accessed only
within
the class and by friend functions of that class. The scope of the private acess specifier is class
level.
2 : public : if a class members that have been declared as a public, it can be accessed outside the
class. The scope of the public acess specifier is global.
3 : protected : A member declared as protected is accessible by the member functions within its
class and any class immediately derived from it. It cannot be accessed by the functions outside
these two classes.
Constructors & Destructors
Constructors : A constructor is a special member function that is used to initialize the objects
of
its class. The purpose of the constructor is to initialize the variables.
A constructor has the following characterstics.
1 : They should be declared in the public section.
2 : The constructor’s name and class name should be same. And the constructor’s name should
end with a pair of simple braces.
3 : A constructor may have or may not have parameters. If a constructor does not have any
parameters, then it is called default constructor.
4 : A constructor does not return any value, not even ‘void’.
5 : A constructor is automatically called and executed at the time of creating an object. While
creating an object, if nothing is passed to the object, the default constructor is called and
executed.
If some values are passed to the object, then the parameterized constructor is called.
Ex : person p1; // default constructor
Person p1(10,20); // parameterized constructor
6 : A constructor is called and executed only once per object. This means when we creat an
object,
the constructor is called. When we create second object, again the constructor is called second
time.
Syntax : class classname
{
private :
private variables;
public :
classname(); // Constructor
};
Constructor Definition :
classname :: classname()
{
//body definition;
}
Example :
#include<iostream.h>
class test
{
private :
int x,y;
public :
test();
void getdata();
};
test :: test()
{
x=5;
y=10;
}
void test :: getdata()
{
cout<<”x=”<<x<<endl;
cout<<”y=”<<y<<endl;
}
int main()
{
test t;
[Link]();
return 0;
}
Output : x=5,y=10
Parameterized constructor : if a constructor has one or more parameters are called
parameterized constructor.
Syntax : class classname
{
private :
private members;
public :
classname(parameter1,parameter2);
};
Parameterized constructor Definition :
classname :: classname(parameter1,parameter2)
{
//body definition;
}
Example :
#include<conio.h>
class Test
{
private:
int x,y;
public:
Test(int a,int b);
void getdata();
};
Test :: Test(int a,int b)
{
x=a;
y=b;
}
void Test ::getdata()
{
cout<<"x value is:"<<x<<"\n";
cout<<"y value is:"<<y;
}
int main()
{
clrscr();
Test t(40,50);
[Link]();
return 0;
}
Constructor Overloading : writing two or more constructors with the same name but with
different parameters is called constructor overloading. Constructors are useful to perform
different
tasks.
Ex : class sample
{
public :
int x,y;
sample() //Default Constructor
{
x=y=0;
}
sample(int i) //Parameterized constructor
{
x=y=i;
}
sample(int i,int j) //Parameterized constructor
{
x=i;
y=i;
}
};
int main()
{
sample t; //default constructor is called
sample t1(5);
sample t2(2,8);
cout<<”t.x”<<t.x<<”,t.y:”<<t.y<<”\n”;
cout<<”t1.x”<<t1.x<<”,t1.y:”<<t1.y<<”\n”;
cout<<”t2.x”<<t2.x<<”,t2.y:”<<t2.y<<”\n”;
}
What is diff between default constructor and parameterized constructor?
Defalt constructor Parameterized constructor
1 : is useful to initialize all objects with same 1 : is useful to initialize each object with
data different data.
2 : does not have any parameters 2 : Will have one or more paramentets
3 : when data is not passed at the time of 3 : when data passed at the time of creating
creating an object. Default constructor is an object. Parameterized constructor is
called. called.
What is diff between a constructor and a method?
Constructors Methods
1 : is used to initialize the variables of a 1 : Is used for any general purpose
class. processing or caluculations.
2 : A constructor’s name and class name 2 : A method name and class name can be
should be same. same or different.
3 : a constructor is called at the time of 3 : A method can be called after creating the
creating object. object.
4 : A constructor is called only once per 4 : A method can be called several times on
object the object.
5 : A constructor is automatically called and 5 : A method is executed only when we call
executed. it.
Copy Constructor : A constructor takes a reference to an object of same class as an argument is
known as copy constructor.A reference variable has been used as an argument to the copy
constructor. We cannot pass the argument by value to a copy constructor.
Syntax : class classname
{
private :
private members;
public :
classname(); //default constructor
classname(parameter1,parameter2); //Parameterized constructor
classname(classname &obj); //copy constructor.
};
A copy constructor is used to declare and initialize an object from another object.
While invoking the copy constructor we will use the following syntax
classname new_objectname(old_objectname);
#include<iostream.h>
class sample
{
int x,y;
public :
sample();
sample(int a,int b);
sample(sample &sam);
void display()
{
cout<<"x value is:"<<x<<"\n";
cout<<"y value is :"<<y<<"\n";
}
};
sample :: sample()
{
}
sample :: sample(int a,int b)
{
x=a;
y=b;
}
sample :: sample(sample &sam)
{
x=sam.x;
y=sam.y;
}
void main()
{
sample s;
[Link]();
sample s1(10,20);
[Link]();
sample s3(s1);
[Link]();
sample s4=s;
[Link]();
}
Destructors : Destructor is used to destroy the objects that have been created by a constructor.
Destructor is a member function whose name is the same as the class name but it is preceded by
a
tilde.
Syntax : ~classname(); // Destructors
A destructor takes no arguments and has no return type. Destructors cannot be declared static,
const. A destructor can be declared virtual or pure virtual.
#include<iostream.h>
int n=0;
class call
{
public:
call ()
{
cout<<”\n constructor”<<++n;
}
~call ()
{
cout<<”\n destructor”< --no;
}
};
int main ()
{
call c1, c2;
return 0;
}
Friend Function : friend function is a function that is not a member function of that class,
but
it can acess the private and protected members of the class.
Friend function declaration :
class classname
{
public :
friend returntype functionname(object);
};
The function declaration should be preceded by the keyword friend. The function is defined is
like
a normal c++ function. The function definition does not use either the keyword friend or the
scope
operator ::. The functions that are declared with the keyword friend are known as friend
function.
A friend function has certain special characterstics.
1 : It is not in the scope of the class to which it has been declared as friend.
2 : It is not in the scope of the class, It cannot be called using the object of that class.
3 : It can be invoked like a normal function without the help of any object.
4 : It cannot acess the member names directly and has to use an object name and dot operator
with
each member name.
5 : it can be declared either in private part and public part.
6 : It has the objects as arguments.
#include<iostream.h>
class sample
{
int a,b;
public :
void setvalue()
{
a=25,b=40;
}
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a+s.b)/2.0;
}
void main()
{
sample X;
[Link]();
cout<<"mean value:"<<mean(X)<<"\n";
}
C++ Friend class
A friend class can access both private and protected members of the class in which it has been declared as
friend.
Example of a friend class.
#include <iostream>
using namespace std;
class A
{
int x =5;
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;
B b;
[Link](a);
return 0;
}
Dynamic memory allocation and Deallocation (New and Delete )
Dynamic memory allocation :
1 : It refers to the allocation of memory to the program during their execution.
2 : The memory is allocated from a free store called heap.
3 : It is used the amount of memory required by a program is not known in advance.
4 : The memory is allocated using a new operator.
New Operator : The new operator is used to create a heap memory space for an object of a
class.
C++ provides a new operator in which an object can be dynamically memory is allocated.
The new operator has following 3 steps.
1 : find storage for the object to be created.
2 : Initilize that object.
3 : Return a suitable pointer type to the object.
Syntax : datatype pointer_variable = new datatype;
Where datatype can be a int, float, char, array or even class object.
The new operator returns a pointer to the object created. Functions cannot be allocated
by
using the new operator but pointers to functions can be used for allocating memory space.
Ex : int *ptr = new int; // memory for a integer is allocated.
Dynamic memory Deallocation :
1 : it refers to the release of the allocated memory by the program during their execution.
2 : The memory is returned to the heap.
3 : The allocated memory is released by using an operator is called “delete”.
Delete Operator : The delete operator is used to destroy the variable space which has been
created by using the new operator dynamically. The memory is then released to the heap so that
it
can be utilized by some other object.
Syntax : delete pointer_variable;
As the new operator return a pointer to the object being created, the delete operator
must
define a pointer name only but not with data type. The delete operator takes no arguments for
deleting a single instance of a memory variable created by a new operator.
Example : using new and delete operators
#include<iostream.h>
void main()
{
int *ptr_a = new int;
int *ptr_b = new int;
int *ptr_sum = new int;
int *ptr_sub = new int;
int *ptr_mul = new int;
int *ptr_div = new int;
cout<<”Enter any two integers:”;
cin>>*ptr_a>>*ptr_b;
*ptr_sum = *ptr_a + *ptr_b;
*ptr_sub = *ptr_a - *ptr_b;
*ptr_mul = *ptr_a * *ptr_b;
*ptr_div = *ptr_a / *ptr_b;
cout<<”the addition is:”<<*ptr_sum<<endl;
cout<<”the subtraction is:”<<*ptr_sub<<endl;
cout<<”the multiplication is:”<<*ptr_mul<<endl;
cout<<”the division is:”<<*ptr_div<<endl;
delete ptr_a;
delete ptr_b;
delete ptr_sum;
delete ptr_sub;
delete ptr_mul;
delete ptr_div;
}
this pointer : we know that a pointer is variable which holds the memory address of another
variable. The this pointer is a variable which is used to acess the address of the class it self.
Sometimes , the this pointer may have return data items to the caller.
Example by using this pointer :
#include<iostream.h>
class sample
{
int x;
public :
void display()
{
cout<<”object address:”<<this;
}
}
void main() OUTPUT: object address : 0x24e0fff2
{
sample s;
[Link]();
}
// for accessing member data with this pointer
#include<iostream.h>
class sample
{
int x;
public :
void setdata(int a);
void display(); OUTPUT : contents of the value : 20.
};
void sample :: setdate(int a)
{
x=a;
}
void sample :: display()
{
cout<<”contents of the value :”<<this->x;
}
void main()
{
sample s;
[Link](20);
[Link]();
}
Abstraction in C++
Data abstraction is one of the most essential and important feature of object oriented
programming in C++. Abstraction means displaying only essential information and
hiding the details. Data abstraction refers to providing only essential information about
the data to the outside world, hiding the background details or implementation.
Abstraction using Classes: We can implement Abstraction in C++ using classes. Class
helps us to group data members and member functions using available access
specifiers. A Class can decide which data member will be visible to outside world and
which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files.
For example, consider the pow() method present in math.h header file. Whenever we
need to calculate power of a number, we simply call the function pow() present in the
math.h header file and pass the numbers as arguments without knowing the underlying
algorithm according to which the function is actually calculating power of numbers.
Abstraction using access specifiers
Access specifiers are the main pillar of implementing abstraction in C++. We can use
access specifiers to enforce restrictions on class members. For example:
Members declared as public in a class, can be accessed from anywhere in the
program.
Members declared as private in a class, can be accessed only from within the
class. They are not allowed to be accessed from any part of code outside the class.
We can easily implement abstraction using the above two features provided by access
specifiers. Say, the members that defines the internal implementation can be marked as
private in a class. And the important information needed to be given to the outside
world can be marked as public. And these public members can access the private
members as they are inside the class.
#include <iostream>
using namespace std;
class implementAbstraction
{
private:
int a, b;
public:
// method to set values of
// private members
void set(int x, int y)
{
a = x;
b = y;
}
void display()
{
cout<<"a = " <<a << endl;
cout<<"b = " << b << endl;
}
};
int main()
{
implementAbstraction obj;
[Link](10, 20);
[Link]();
return 0;
}
Advantages of Data Abstraction:
Helps the user to avoid writing the low level code
Avoids code duplication and increases reusability.
Can change internal implementation of class independently without affecting the
user.
Helps to increase security of an application or program as only important details
are provided to the user.
Abstract Data Types(ADT):
Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by
a set of value and a set of operations.
The definition of ADT only mentions what operations are to be performed but not how
these operations will be implemented. It does not specify how data will be organized in
memory and what algorithms will be used for implementing the operations. It is called
“abstract” because it gives an implementation-independent view. The process of
providing only the essentials and hiding the details is known as abstraction.
The user of data type does not need to know how that data type is implemented, for
example, we have been using Primitive values like int, float, char data types only with
the knowledge that these data type can operate and be performed on without any idea
of how they are implemented. So a user only needs to know what a data type can do,
but not how it will be implemented. Think of ADT as a black box which hides the inner
structure and design of the data type.
Stack ADT
In Stack ADT Implementation instead of data being stored in each node, the
pointer to data is stored.
The program allocates memory for the data and address is passed to the stack
ADT.
The head node and the data nodes are encapsulated in the ADT. The calling
function can only see the pointer to the stack.
The stack head structure also contains a pointer to top and count of number of
entries currently in stack.
//Stack ADT Type Definitions
typedef struct node
{
void *DataPtr;
struct node *link;
} StackNode;
typedef struct
{
int count;
StackNode *top;
} STACK;
A Stack contains elements of the same type arranged in sequential order. All operations
take place at a single end that is top of the stack and following operations can be
performed:
push() – Insert an element at one end of the stack called top.
pop() – Remove and return the element at the top of the stack, if it is not empty.
peek() – Return the element at the top of the stack without removing it, if the
stack is not empty.
size() – Return the number of elements in the stack.
isEmpty() – Return true if the stack is empty, otherwise return false.
isFull() – Return true if the stack is full, otherwise return false.
Information Hiding in C++
Information hiding is a process of combining data and functions into a single unit. The ideology
behind data hiding is to conceal data within a class, to prevent its direct access from outside the
class. It helps programmers to create classes with unique data sets and functions, avoiding
unnecessary penetration from other program classes.
Const member functions in C++
Like member functions and member function arguments, the objects of a class can also
be declared as const. an object declared as const cannot be modified and hence, can
invoke only const member functions as these functions ensure not to modify the object.
A const object can be created by prefixing the const keyword to the object declaration.
Any attempt to change the data member of const objects results in a compile-time
error.
Syntax:
const Class_Name Object_name;
When a function is declared as const, it can be called on any type of object,
const object as well as non-const objects.
Whenever an object is declared as const, it needs to be initialized at the time of
declaration. however, the object initialization while declaring is possible only with
the help of constructors.
A function becomes const when the const keyword is used in the function’s declaration.
The idea of const functions is not to allow them to modify the object on which they are
called. It is recommended the practice to make as many functions const as possible so
that accidental changes to objects are avoided.
Following is a simple example of a const function
#include<iostream>
using namespace std;
class A{
public:
int x;
A()
{
x=15;
}
void print()
{
cout<<"print method"<<endl;
}
int display() const
{
//x=18 //error because function is const
return x;
}
};
int main()
{
const A o1;
A o2;
[Link]();
[Link]();
//[Link]();//error becasue print is non- const and o1 is const
[Link]();
// cout<<[Link]()<<endl;
// o1.x=17;//error because object is const
cout<<o1.x<<endl;