Unit III Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 70

UNIT-III

CLASSES AND OBJECTS


 Class: A class in C++ is the building block, that leads to Object-
Oriented programming.
 A class is used to pack data and functions together.
 It is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an
instance of that class.
 When defining a clSS , WE RE CREATINGAbstract data type that
can be used as basic data type.
 A class is used to specify the form of an object and it combines data
representation and methods for manipulating that data into one neat
package.
 The data and functions within a class are called members of the class.
 A class specification has two parts
(i) class declaration
(ii) class function definitions

• Class declaration : describes the type and scope of its members


• Class function definition : describe how the class functions are
implemented
General form:

(i) Class declaration


class classname
{ private:
Variable declarations;
Function declarations;

public:
Variable declarations;
Function declarations;
};
the class declaration is similar to structure declaration
the keyword class specifies that it follows an abstract data of type class name.the body of the class is
enclosed within braces and terminated by a semicolon(;)

• The members that have been declared as private can be accessed onlyfrom with in the class.
• public members can be accessed from outside the class also.
• 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
member functions.
• Only the member functions can have access to the private data members and private functions.
• However, the public members can be accessed from the outside the class.
• The binding of data and functions together into a single class type variable is referred to as
encapsulation.

Therefore, any member that is declared before any other access specifier has private access automatically.
For example:

class Rectangle
{
int width, height;
public:
void set_values (int,int);
int area (void);
} rect;

Example:

class student

private :
int roll;

char name[30];

public:

void get_data()

cout<<”Enter roll number and name”:

cin>>roll>>name;

void put_data()

cout<<”Roll number:”<<roll<<endl;

cout<<”Name :”<<name<<endl;

};

Declaring Object
• Instance of a class is called
object.
• A class is template for an object
and an object is instance of a
class
Syntax:
class_name object_name;
Ex:
student s;
• Once a class has been declared we can create variables of that type by using the class name.
• In C++, the class variables are known as objects.

class item

-----------

-----------

-----------

};

Example:

item x;

• creates a variables x of type item. Therefore

x is called an object of type item.


ACCESSING CLASS MEMBER
• The private data of a class can be accessed only through the member
functions of thatclass.
Syntax:
object name.function-name(actual arguments);
#include<iostream.h>
class student
{
private:
int roll;
char name[20];
public:
void getdata()
{ cout<<”Enter Roll number:”;
cin>>roll;
cout<<”Enter Name:”;
cin>>name;
}
Example 1: Object and Class in C++ Programming

// Program to illustrate the working of objects and class in C++


Programming
#include <iostream.h>
// create a class
class Room {
public:
double length;
double breadth;
double height;
double calculateArea()
{
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
Use of public, private and protected keywords

• Access Specifiers
– public
• may be accessible from anywhere within a program or
• members are accessible from outside the class
– private
• may be accessed only by the member functions, and friends of
this class
• members cannot be accessed (or viewed) from outside the
class
– protected
• members cannot be accessed from outside the class,
however, they can be accessed in inherited classes.
• acts as public for derived classes
• behaves as private for the rest of the program

Public keyword
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
If you try to access a private member, an error occurs:
error: y is private
• By default, all members of a class
are private if you don't specify an
access specifier:
Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
# include <iostream.h>
// class definition
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}

};
// main function
int main()
{
Circle obj;

// accessing public datamember outside class


obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";


cout << "Area is: " << obj.compute_area();
return 0;
}
Output:
Radius is: 5.5
Area is: 94.985

Defining member
functions
(a) Private or public section
(b) Inside or outside the class
(i)Member function inside the class

//Write a program to read data of a student


#include<iostream.h>
class student
{
private:
int roll;
char name[20];
public:
void getdata()
{
cout<<”Enter Roll number:”;
cin>>roll;
cout<<”Enter Name:”;
cin>>name;
}
void putdata()
{
cout<<”Roll no:”<<roll<<endl;
cout<<Name:”<<name<<endl;
}
};
int main()
{
student s;
clrscr();
s.getdata();
s.putdata();
returm 0;
}
// C++ program to demonstrate private
// access modifier

#include<iostream.h>
using namespace std;

class Circle
{
// private data member
private:
double radius;

// public member function


public:
double compute_area()
{
// member function can access private

cout << "Area is:" <<


obj.compute_area();

// data member radius


return 3.14*radius*radius;
}

};

// main function
int main()
{
// creating object of the class
Circle obj;

// trying to access private data member


// directly outside the class
obj.radius = 1.5;
return 0;
}

(ii)Member function ouside the class

#include <iostream.h>
#include<conio.h>
class Cube
{
public:
int side;
int getVolume();
};
// member function defined outside class definition
int Cube :: getVolume()
{
return side*side*side;
}
int main()
{
Cube C1;
clrscr();
C1.side = 4; // setting side value
cout<< "Volume of cube C1 = "<< C1.getVolume();
getch();
}
Exercise
(a)Write a program to add two numbers by using the concept member
function outside the class
(b) Write a program to find largest of two numbers by using the
concept member function outside the class
Write a program to find largest of two numbers by using the concept member
function outside the class

#include <iostream.h>
#include<conio.h>
class set
{
int m,n;
public:
void input(void);
void display(void);
int largest(void);
};
// member function defined outside class definition
int set :: input()
{
cout<< "enter values of m,n \n"<<;
cin>>m>>n;
}
int set::largest(void)
{
if(m>n)
return(m);
else
return(n);
}
void set::display(void)
{
cout<<"largest value="<<largest()<<"\n";
}
int main()
{
set A;
clrscr();
A.input()
A.display();
getch();
}
(iii)Member function in Public section
# include <iostream.h>
// class definition
class Circle
{
public:
double radius;

double compute_area()
{
return 3.14*radius*radius;
}

};

// main function
int main()
{
Circle obj;
// accessing public datamember outside class
obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";


cout << "Area is: " << obj.compute_area();
return 0;
}

Output:
Radius is: 5.5
Area is: 94.985
// 1. ACCESS PUBLIC MEMBERS USING OBJECTS
#include<iostream.h>
#include<conio.h>
class item
{
public :
int itemcode;
float price;
int quantity;
};
void main()
{
item one;
clrscr();
one.itemcode=1001;
one.price=80.50;
one.quantity=2;
cout<<"\n\t\t ITEM DETAILS";
cout<<"\n\t Item code :"<<one.itemcode;
cout<<"\n\t Item price :"<<one.price;
cout<<"\n\t Item quantity:"<<one.quantity;
getch();
}
(IV)Member function in
private section
#include <iostream.h>
#include<conio.h>
class ITEM
{
int numberr;
float cost
void values()
{
number=123;
cost=53.5;
}
public:
void show()
{
values();
cout<<"\n\t Item code :"<<number;
cout<<"\n\t Item price :"<<cost;
}
};
int main()
{
ITEM A;
clrscr();
A.show();
getch();
}
Data Hiding or Encapsulation
• Data Hiding is also known as
encapsulation
• Process of forming objects and
encapsulated object is called as an
abstract data type
• Data Hiding is nothing but making data
variable of the class private.
• Private data cannot be accessed Directly
by the object
• The objects using public member
functions of the same class can access
the Private data of the class
• Keywords private and protected are used
for hiding the data
// example program to calculate simple interest
//hide the sata elements of the class using private keyword
#include<iostream.h>
#include<conio.h>
class interest
{
private:
float pamount,rate, period;
float interest,totalAmount;
public:
void input()
{
cout<<"Enter principal amount:";
cin>>pamount;
cout<<"\nEnter Rate of Interest:";
cin>>rate;
cout<<"\nNumber of Years:";
cin>>period;
interest=(pamount*period*rate)/100;
totalAmount=interest+pamount;
}
void show()
{
cout<<"\nOUTPUT"<<"\n~~~~~~~~";
cout<<"\nPrincipal Amount:"<<pamount;
cout<<"\nInterest :"<<interest;
cout<<"\nTotal Amount :"<<totalAmount;
}
};
void main()
{
clrscr();
interest r;
r.input();
r.show();
getch();
};
Classes, objects and
memory
• Objects are identifiers declared for class
type
• Object is a composition of one or more
variables declared inside the class
• Each object has its own copy of public
and Private data members
• An object can have access to its own
copy of data members and have no
access to the data members of other
objects
• Declaration of a class does not allocate
memory
• When an object is declared, memory is
reserved for data members only and not
for Member functions
Note:
• Member function are created and memory
is allocated to them only once when a
class declared.
• All objects of a class access the same
memory location where member functions
are stored. Hence, separate copies of
member functions are not present in every
object like member variables
Classes, objects and
memory- EXAMPLE
//program to decalre objects and display their contents
#include <iostream.h>
#include<conio.h>
class month
{
public:
char *name;
int days;
};
void main()
{
month M1,M2;;
clrscr();
M1.name="January:"; // object declaration
M1.days=31;
M2.name="April";
M2.days=30;
cout<< "OBJECT M1: \n ADDRESS ";
cout<<(unsigned)&M1.name;
cout<<"\nMonth M1 Days Address:"<<(unsigned)&M1.days;
cout<< "\nOBJECT M2: \n ADDRESS ";
cout<<(unsigned)&M2.name;
cout<<"\nMonth M1 Days Address:"<<(unsigned)&M2.days;
getch();
}

Example program to display the


size of the object
//program to display object size
#include <iostream.h>
#include<conio.h>
class data
{
public:
long i;
float f;
char c;
};
int main()
{
data M1,M2;;
clrscr();
cout<<"\nsize of object M1="<<sizeof(M1);
cout<<"\nsize of object M2="<<sizeof(M2);
cout<<"\nsize of class data="<<sizeof(data);
M1.i=34.0005;
M1.f=1.5;
M1.c='b';
cout<<"\nsize of object after value assignment
M1="<<sizeof(M1);
return 0;
}

Note:
• The sizeof() operator displays
the size of objects.
• The size of any object is equal
to sum of sizes of all the data
members of the class.
• Member functions are not
considered in the size of object.
• All the objects of a class use
the same member functions.
• Only one copy of Member
function is created and stored
in the memory whereas each
object has its own set of data
members.

Static member
variables and functions
C++ introduces two more uses for the static keyword
when applied to classes:
(i) static member variables, and
(ii) static member functions.
(i)Static member variables
• Data member of a class can be qualified
us static. the properties of a static
variable are,
A static variable is initialized to 0 when the
first object of its class is created. No other
initialization is permitted.
 only one copy of the member is
created for the entire class and is
shared by all the objects of the
class, no matter how many objects
are created.
 It is visible only within the class,
but its lifetime is the entire program.
• Static Keyword is used to preserve value
of a variable.
• static function or are data element is only
recognized inside the scope of the present
class.
Syntax:
static<variable definition>;
Example:
static int c;
The class and scope of the static
member variable is defined outside the
class declaration is
class_name :: static_data_member;
Ex. int sumnum::c=0;
//program to declare and display value of static
data member
# include<iostream.h>
# include <conio.h>
class number
{
staic int c;
public:
void count()
{
++c;
cout<<"\n c="<<c;
}
};
int number::c=0;
int main()
{
int number a,b,c;
clrscr();
a.count();
b.count();
c.count();
return 0;
}
Output
c=1
c=2
c=3

Example (static
member)
#include <iostream>
using namespace std;
class Demo
{
private:
static int X;
public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};
//defining
int Demo :: X =10;
int main()
{
Demo X;
X.fun();

return 0;
}
Output
Value of X: 10
Showing difference between static and non-static
member variables
// 4. STATIC AND NONSTATIC MEMBER VARIABLES
#include<iostream.h>
#include<conio.h>
class number
{
static int count;
int k;
public:
void zero()
{
k=0;
}
void add()
{
++count;
++k;
cout<<"\t\n\n Value of count ="<<count
<<"\t\n Address of count ="<<(unsigned)&count;

cout<<"\t\n Value of k="<<k


<<"\t\n Address of k="<<(unsigned)&k;
}
};
int number::count=0;
void main()
{
number A,B,C; // object creation
clrscr();
cout<<"STATIC AND NONSTATIC MEMBER VARIABLES";
A.zero();
B.zero();
C.zero();
A.add();
B.add();
C.add();
getch();
}

(iii) Static member functions.


Syntax
static<function definition>;
Example:
static void display()
{}
 Functions can also be declared as static
 When a function is defined as static , it can access only
static member variables and functions of the same
class.
 The non static members are not available to these
functions
 The static member functions can be invoked using its
class name without using its objects

 The programmer must follow the


following things
 Just one copy of the static member
is created in the memory for entire
class. all objects of the the entire
class share the same copy of the
static member
 static member functions Can access
only static data members or functions
 static member functions can be
invoked using class name
 it is also possible to invoke static
member functions using objects
 when one of the objects changes the
value of data member variables, the
effect is visible to all the objects of
the class
 the syntax for calling static Member
function is
class name:: function name
• Properties of static
member functions:
1.A static function can only
access other static
variables or functions
present in the same class
2.Static member functions
are called using the class
name. Syntax
class_name::function_name( )
#include <iostream>

using namespace std;

class Example{
static int Number;
int n;

public:

void set_n()
{

n = ++Number;
}

void show_n()
{

cout<<"value of n = "<<n<<endl;
}

static void show_Number(){

cout<<"value of Number = "<<Number<<endl;


}

};

int Example:: Number;

int main()
{
Example example1, example2;

example1.set_n();
example2.set_n();

example1.show_n();
example2.show_n();

Example::show_Number();

return 0;
}
• static private member function can be
declared in private section.
• The private function must be invoked using
static public function
• Static public member variable can be
initialised in function main like other
variables.
• static member variable using class name and
scope access operator can be accessed.
• scope access operator is also used when
variables of same name are declared in global
and local scope
• example program to declare static public
member variable
• global and local variable with same name
static object
• the object is composition of one or more member
variables. constructor is used to initialise variables of the
object to decide values
• the keyword static can be used to initialise all class data
member variables to zero
• when declaring object as static can initialise the objects
associated members to zero

Array of Objects in
c++
• The array of type class
contains the objects of the
class as its individual elements.
Thus, an array of a class type
is also known as an array of
objects. An array of objects is
declared in the same way as
an array of any built-in data
type.
#include <iostream.h>
#include <string.h>
class Student
{
string name;
int marks;
public:
void getName()
{
getline( cin, name );
}
void getMarks()
{
cin >> marks;
}
void displayInfo()
{
cout << "Name : " << name << endl;
cout << "Marks : " << marks << endl;
}
};
int main()
{
Student st[5];
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
cout << "Enter name" << endl;
st[i].getName();
cout << "Enter marks" << endl;
st[i].getMarks();
}
for( int i=0; i<5; i++ )
{
cout << "Student " << i + 1 << endl;
st[i].displayInfo();
}
return 0;
}
Student st[5]; - We created an array of 5 objects of the
Student class where each object represents a student having
a name and marks.
The first for loop is for taking the input of name and marks
of the students. getName() and getMarks() are the
functions to take the input of name and marks respectively.
The second for loop is to print the name and marks of all the
5 students. For that, we called the displayInfo() function for
each student.
//5. ARRAY OF OBJECTS
#include<iostream.h>
#include<conio.h>
class student
{
char name[20];
int roll;
int mark1,mark2;
public:
void input(void);
void display(void);
};
void student::input()
{
cout<<"\n Enter student name:";
cin>>name;
cout<<"\n Enter roll number:";
cin>>roll;
cout<<"\n Enter mark1:";
cin>>mark1;
cout<<"\n Enter mark2:";
cin>>mark2;
}
void student::display()
{
cout<<name<<"\t"<<roll<<"\t\t "<<mark1<<"\t"<<mark2<<endl;
}
void main()
{
clrscr();
student s1[3];
cout<<"\n Enter student details";
for(int i=0;i<3;i++)
s1[i].input();
cout<<"\n\n\t STUDENT DETAILS";
cout<<"\n\t ~~~~~~~~~~~~~~~";
cout<<"\n NAME\tROLL NUMBER \t MARK1\tMARK2\t\n";
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
for(i=0;i<3;i++)
s1[i].display();
getch();
}
Passing and Returning Objects in C++

(i)Passing an Object as argument


• To pass an object as an argument we write
the object name as the argument while calling
the function the same way we do it for other
variables.
• Syntax: function_name(object_name);
/ /C++ program to show passing of objects to a function

#include <iostream.h>

class Example {
public:
int a;

// This function will takean object as an argument


void add(Example E)
{
a = a + E.a;
}
};

// Driver Code
int main()
{

// Create objects
Example E1, E2;

// Values are initialized for both objects


E1.a = 50;
E2.a = 100;

cout << "Initial Values \n";


cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n";

// Passing object as an argument to function add()


E2.add(E1);

// Changed values after passing


// object as argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n";

return 0;
}
output:
Initial Values
Value of object 1: 50
& object 2: 100
New values
Value of object 1: 50
& object 2: 150
(ii) Returning Object as argument
syntax
object = return object_name;
When the object E3 calls the add function it passes the other
two objects namely E1 & E2 as arguments. Inside the function,
another object is declared which calculates the sum of all the
three variables and returns it to E3.
This code and the above code is almost the same, the only
difference is that this time the add function returns an object
whose value is stored in another object of the same class
‘Example’ E3. Here the value of E1 is displayed by object1, the
value of E2 by object2 and value of E3 by object3.
// C++ program to show passing of objects to a function
#include <iostream.h>
class Example {
public:
int a;

// This function will take object as arguments and return object


Example add(Example Ea, Example Eb)
{
Example Ec;
Ec.a = 50;
Ec.a = Ec.a + Ea.a + Eb.a;

// returning the object


return Ec;
}
};
int main()
{
Example E1, E2, E3;

// Values are initialized for both objects


E1.a = 50;
E2.a = 100;
E3.a = 0;

cout << "Initial Values \n";


cout << "Value of object 1: " << E1.a << ", \nobject 2: " << E2.a
<< ", \nobject 3: " << E3.a << "\n";
// Passing object as an argument to function add()
E3 = E3.add(E1, E2);

// Changed values after passing object as an argument


cout << "New values \n";
cout << "Value of object 1: " << E1.a << ", \nobject 2: " << E2.a
<< ", \nobject 3: " << E3.a << "\n";

return 0;
}
Output:
Initial Values
Value of object 1: 50,
object 2: 100,
object 3: 0
New values
Value of object 1: 50,
object 2: 100,
object 3: 200

C++ Friend Functions


• A friend function of a class is defined outside that class'
scope but it has the right to access all private and
protected members of the class. Even though the
prototypes for friend functions appear in the class
definition, friends are not member functions.
• A friend can be a function, function template, or member
function, or a class or class template, in which case the
entire class and all of its members are friends.
• To declare a function as a friend of a class, precede the
function prototype in the class definition with
keyword friend as follows −
class class_name
{
friend data_type function_name(argum
ent/s);
};
class demo
{
data members :
public :
members functions;
// friend function declaration
friend data_type function_name (parameters);
};
data_type function_name (parameters)
//definition
{
function definition;
}
Characteristics of a Friend function:
• The function is not in the scope of the class to which
it has been declared as a friend.
• It cannot be called using the object as it is not in the
scope of that class.
• It can be invoked like a normal function without
using the object.
• It cannot access the member names directly and
has to use an object name and dot membership
operator with the member name.
• It can be declared either in the private or the public
part.
//6.FRIEND FUNCTION

#include<iostream.h>
#include<conio.h>
class account
{
private:
char name[20];
int accno;
float bal;
public:
void read()
{
cout<<" Enter account holder name:";
cin>>name;
cout<<"\n Enter accout number :";
cin>>accno;
cout<<"\n Enter balance :";
cin>>bal;
}
friend void showbal(account);
};
void showbal(account ac)
{
cout<<"\n Balance of Account no:";
cout<<ac.accno<<" is Rs."<<ac.bal;
}
void main()
{
clrscr();
account obj;
cout<<"\tFRIEND FUNCTION\n";
cout<<"\t~~~~~~~~~~~~~~~\n";
obj.read();
showbal(obj);
getch();
}

class Box {
double width;

public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place a following
declaration in the definition of class ClassOne −

friend class ClassTwo;


Consider the following program −

Live Demo
#include <iostream>

using namespace std;

class Box {
double width;

public:
friend void printWidth( Box box );
void setWidth( double wid );
};

// Member function definition


void Box::setWidth( double wid ) {
width = wid;
}

// Note: printWidth() is not a member function of any class.


void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}

// Main function for the program


int main() {
Box box;

// set box width without member function


box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return 0;
}

C++ Recursion
• When function is called within the same function, it is known as recursion in C++. The function which calls the
same function, is known as recursive function.
• A function that calls itself, and doesn't perform any task after function call, is known as tail recursion. In tail
recursion, we generally call the same function with return statement.

recursionfunction(){
recursionfunction(); //calling self function
}
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
Output:

Enter any number: 5


Factorial of a number is: 120

1. Write a program in C to print first 50 natural numbers using


recursion. Go to the editor
Expected Output :

The natural numbers are : 1 2 3


4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21
22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38
39 40 41 42 43 44 45 46 47
48 49 50
Click me to see the solution

2. Write a program in C to calculate the sum of numbers from 1 to n


using recursion. Go to the editor
Test Data :
Input the last number of the range starting from 1 : 5
Expected Output :

The sum of numbers from 1 to 5 :


15
Click me to see the solution

3. Write a program in C to Print Fibonacci Series using recursion.


Go to the editor
Test Data :
Input number of terms for the Series (< 20) : 10
Expected Output :

Input number of terms for the Series (< 20) : 10


The Series are :
1 1 2 3 5 8 13 21 34 55
Click me to see the solution

4. Write a program in C to print the array elements using recursion.


Go to the editor
Test Data :
Input the number of elements to be stored in the array :6
Input 6 elements in the array :
element - 0 : 2
element - 1 : 4
element - 2 : 6
element - 3 : 8
element - 4 : 10
element - 5 : 12
Expected Output :

The elements in the array are : 2 4 6 8 10 12


Click me to see the solution

5. Write a program in C to count the digits of a given number using


recursion. Go to the editor
Test Data :
Input a number : 50
Expected Output :

The number of digits in the number is : 2


Click me to see the solution

6. Write a program in C to find the sum of digits of a number using


recursion. Go to the editor
Test Data :
Input any number to find sum of digits: 25
Expected Output :

The Sum of digits of 25 = 7

Click me to see the solution

7. Write a program in C to find GCD of two numbers using


recursion. Go to the editor
Test Data :
Input 1st number: 10
Input 2nd number: 50
Expected Output :

The GCD of 10 and 50 is: 10


Click me to see the solution

8. Write a program in C to get the largest element of an array using


recursion. Go to the editor
Test Data :
Input the number of elements to be stored in the array :5
Input 5 elements in the array :
element - 0 : 5
element - 1 : 10
element - 2 : 15
element - 3 : 20
element - 4 : 25
Expected Output :

Largest element of an array is: 25


Click me to see the solution

9. Write a program in C to reverse a string using recursion. Go to the


editor
Test Data :
Input any string: w3resource
Expected Output :

The reversed string is: ecruoser3w


Click me to see the solution

10. Write a program in C to find the Factorial of a number using


recursion. Go to the editor
Test Data :
Input a number : 5
Expected Output :

The Factorial of 5 is : 120


Click me to see the solution

11. Write a program in C to convert a decimal number to binary


using recursion. Go to the editor
Test Data :
Input any decimal number : 66
Expected Output :

The Binary value of decimal no. 66 is : 1000010


Click me to see the solution
12. Write a program in C to check a number is a prime number or
not using recursion. Go to the editor
Test Data :
Input any positive number : 7
Expected Output :

The number 7 is a prime number.


Click me to see the solution

13. Write a program in C to find the LCM of two numbers using


recursion. Go to the editor
Test Data :
Input 1st number for LCM : 4
Input 2nd number for LCM : 6
Expected Output :

The LCM of 4 and 6 : 12


Click me to see the solution
14. Write a program in C to print even or odd numbers in given
range using recursion. Go to the editor
Test Data :
Input the range to print starting from 1 : 10
Expected Output :

All even numbers from 1 to 10 are : 2 4 6 8 10


All odd numbers from 1 to 10 are : 1 3 5 7 9
Click me to see the solution

15. Write a program in C to multiply two matrix using recursion. Go


to the editor
Test Data :
Input number of rows for the first matrix : 2
Input number of columns for the first matrix : 1
Input number of rows for the second matrix : 1
Input number of columns for the second matrix : 2
Input elements in the first matrix :
element - [0],[0] : 1
element - [1],[0] : 2
Input elements in the second matrix :
element - [0],[0] : 3
element - [0],[1] : 4
Expected Output :

Here is the elements of First matrix :

1
2
Here is the elements of Second matrix :

3 4
The multiplication of two matrix is :

3 4
6 8
Click me to see the solution

16. Write a program in C to Check whether a given String is


Palindrome or not. Go to the editor
Test Data :
Input a word to check for palindrome : mom
Expected Output :

The entered word is a palindrome.


Click me to see the solution

17. Write a program in C to calculate the power of any number using


recursion. Go to the editor
Test Data :
Input the base value : 2
Input the value of power : 6
Expected Output :

The value of 2 to the power of 6 is : 64


Click me to see the solution

18. Write a program in C to find the Hailstone Sequence of a given


number upto 1. Go to the editor
Test Data :
Input any number (positive) to start for Hailstone Sequence : 13
Expected Output :

The hailstone sequence starting at 13 is :


13 40 20 10 5 16 8 4 2 1
The length of the sequence is 10.
Click me to see the solution

19. Write a program in C to copy One string to another using


recursion. Go to the editor
Test Data :
Input the string to copy : w3resource
Expected Output :

The string successfully copied.

The first string is : w3resource


The copied string is : w3resource
Click me to see the solution
20. Write a program in C to find the first capital letter in a string
using recursion. Go to the editor
Test Data :
Input a string to including one or more capital letters : testString
Expected Output :

The first capital letter appears in the string testString is S.


Click me to see the solution

21. Write a program in C for binary search using recursion. Go to the


editor
Test Data :
Input the number of elements to store in the array :3
Input 3 numbers of elements in the array in ascending order :
element - 0 : 15
element - 1 : 25
element - 2 : 35
Input the number to search : 35
Expected Output :

The search number found in the array.


• Function Overloading in C++
• You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from
each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that
differ only by return type.

#include <iostream>
using namespace std;

class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

int main(void) {
printData pd;

// Call print to print integer


pd.print(5);

// Call print to print float


pd.print(500.263);

// Call print to print character


pd.print("Hello C++");

return 0;
}

Printing int: 5
Printing float: 500.263
Printing character: Hello C++
 What is constructor?
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically
called when object(instance of class) create. It is special member function of the class.
How constructors are different from a normal member function?
 A constructor is different from normal functions in following ways:
 Constructor has same name as the class itself
 Constructors don’t have return type
 A constructor is automatically called when an object is created.
 If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and
has an empty body).
 Types of Constructors in C++
 Constructors are of three types:
 Default Constructor
 Parametrized Constructor
 Copy Constructor
• Default Constructors
• Default constructor is the constructor which doesn't take any argument. It has no parameter.
class Cube
{
public:
int side;
Cube()
{
side = 10;
}
};
int main()
{
Cube c;
cout << c.side;
}
10
In this case, as soon as the object is created the constructor is called which initializes its
data members.
A default constructor is so important for initialization of object members, that even if we
do not define a constructor explicitly, the compiler will provide a default constructor
implicitly.

class integer
{
int m,n; public: integer( );
………..
………..
};
integer :: integer( )
{
m=0; n=0;
}

int main()

{ integer obj1;

There is no need to write any statement to invoke the constructor function.


CHARACTERISTICS OF CONSTRUCTOR
 They should be declared in the public section.
 They are invoked automatically when the objects are created.
 They do not have return type, not even void.
 They cannot be inherited, though a derived class can call the base class constructor.
 Like other c++ functions, they can have default arguments.
 Constructors cannot be virtual.

We cannot refer to their addresses.

They make „implicit calls‟ to the operators new and delete when memory allocation is required.
/*PROG 7.1 DEMO OF CONSTRUCTOR */

#include < iostream.h >

#include < conio.h >

class demo

public:

demo()

cout< <"Hello from constructor \n";

};

void main()

}
clrscr( );

demo d;

getch( )

OUTPUT :

Hello from constructor

The constructors are always declared in the public section. If declared in the private

section then objects are can only be created inside the member functions but serve no

purpose.

2. They are invoked automatically when objects of the class are created. The declaration

demo d; creates an object d which automatically calls the constructor of the class and

prints Hello from constructor.

3. They do not have any return type not even void so they cannot return any value.

4. Constructors cannot be inherited, but they can be called from the constructors of derived

class.

5. Constructors are used to construct the object of the class.

6. The constructor with no argument is known as default constructor of the class. The

default constructor for the class demo will be demo : demo( )

7. Constructors which take arguments like a function takes are known as parameterized

constructor.

8. There is no limit of the number of constructors declared in a class but they all must

conform to rules of function overloading.

9. Constructor can have default arguments.

10. Addresses of constructors cannot be taken.

11. Constructors cannot be virtual.

12. Constructor make implicit calls to operators new and delete in case memory allocation

and de-allocation is to be performed.

The other way to write the above program would be :

#include <iostream.h>

Class demo
{

public :

demo( ); // declaration

};

Working with Constructor and Destructor 281

demo : :demo ( ) // definition

cout<<”Hello from constructor \n”;

void main( )

demo d;

In all
Constructors are of 3 types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor: A constructor that accepts no parameters is called the default constructor.
#include<iostream.h>
#include<conio.h>
class item
{
int m,n;
public:
item()
{
m=10;
n=20;
}
void put();
};
void item::put()
{
cout<<m<<n;
}
void main()
{
item t;
t.put();
getch();
}
2. Parameterized Constructors:-The constructors that take parameters are called
parameterized constructors.
#include<iostream.h>
class item
{
int m,n;
public:
item(int x, int y)
{
m=x;
n=y;
}
};
When a constructor has been parameterized, the object declaration statement such as
item t; may not work. We must pass the initial values as arguments to the constructor function
when an object is declared. This can be done in 2 ways: item t=item(10,20); //explicit call

item t(10,20); //implicit call


Eg:
#include<iostream.h>
#include<conio.h>
class item
{
int m,n;
public:
item(int x,int y)
{
m=x;
n=y;
}
void put();
};
void item::put()
{
cout<<m<<n;
}
void main()
{
item t1(10,20);
item t2=item(20,30);
t1.put();
t2.put();
getch();
}

Constructor are similar to functions but they have the name as class name so similar to functions
which takes argument we can have constructor which can take arguments. The constructor
which
takes parameters is known as parameterized constructor. Again depending upon type of
arguments
and number of arguments they may be overloaded. An example of this is given below :
/*PROG 7.2 DEMO OF PARAMETERIZED CONSTRUCTOR WITH INTEGER DATA*/
#include <iostream.h>
#include <conio.h>
class demo
{
int a,b;
public :
demo( )
{
a=b=0;
cout<<“Zero argument constructor called\n”;
show( );
}
demo(int x, int y)
{
282 Object-Oriented Programming C++ Simplified
a=x;
b=y;
cout<<“Two argument constructor called\n”;
show( );
}
demo(int x)
{
a=b=x;
cout<<“One argument constructor called\n”;
show( );
}
void show( )
{
cout<<“a=”<<a<<“\tb=”<<b<<endl;
}
};
void main( )
{
clrscr( );
demo d1;
demo d2(10,20);
demo d3(30);
getch( );
}
OUTPUT :
Zero argument constructors called
a=0 b=0
Two argument constructor called
a=10 b=20
One argument constructor called
a=30 b=30
/*PROG 7.4 FACTORIAL OF A NUMBER, FACTORIAL OF 6 IS 6*5*4*3*2*1=720*/
#include <iostream.h>
#include <conio.h>
class fact
{
int fa;
int num;
public :
fact( )
{
fa = 1;
cout<<“Enter the number \n”;
cin>>num;
}
int find_fac( )
{
int i;
for(i=1;i<=num;i++)
fa=fa*i;
return fa;
}
void show( )
{
cout<<“The factorial of”<<num<<“is”<<find_fac( )<<endl;
}
};
void main( )
{
clrscr( );
fact obj;
obj.show( );
getch( );
}
OUTPUT :
Enter the number
6
The factorial of6is720

7.4 COPY CONSTRUCTOR


A copy constructor is used to declare and initialized an object from another object when ever
we have statement like demo d2 = d1 (assume demo is class name and d1 is an already
declared object of demo class), they make call to copy constructor defined in the class. When
we have two objects say d1 and d2 and if we write d2=d1 then this results in copying all
members of d1 to d2 but does not call copy constructor. This is simply assignment of one
object to another of same type, but when you want to do something more than merely copying
one object to another you may use copy constructor. For a class demo, copy constructor is
written as :
demo (demo &d)
{
// copy constructor
}
3. Copy Constructor: A copy constructor is used to declare and initialize an object from
another object.
Eg:
item t2(t1);
or
item t2=t1;

1. The process of initializing through a copy constructor is known as copy initialization.


2. t2=t1 will not invoke copy constructor. t1 and t2 are objects, assigns the values of t1 to t2.
3. A copy constructor takes a reference to an object of the same class as itself as
an argument. #include<iostream.h>
class sample
{
int n;
public:
sample()
{ n=
0;
}
sample(int a)
{
n=a;
}
sample(sample &x)
{
n=x.n;
}
void display()
{
cout<<n;
}
};
void main()
{
sample A(100); sample B(A); sample C=A; sample D;
D=A;
A. display();
B. display();
C. display();
D. display();
}

Output: 100 100 100 100

The process of initialization through a copy constructor is known as copy initialization.


Example:-
#incliide<iostream.h>
class code
{
int id;
public
code ( ) { } //constructor
code (int a) { id=a; } //constructor
code(code &x)
{
Id=x.id;
}
void display( )
{
cout<<id;
}
};
int main( )
{
code A(100);
code B(A);
code C=A;
code D;
D=A;
cout<<” \n id of A :”; A.display( );
cout<<” \nid of B :”; B.display( );
cout<<” \n id of C:”; C.display( );
cout<<” \n id of D:”; D.display( );
}
output :-
id of A:100
id of B:100
id of C:100
id of D:100

Multiple Constructors in a Class: Multiple constructors can


be declared in a class. There can be any number of
constructors in a class.
class complex
{
float real,img; public:
complex()//default constructor
{
real=img=0;
}
complex(float r)//single parameter parameterized
constructor
{
real=img=r;
}
complex(float r,float i) //two parameter parameterized
constructor
{
real=r;img=i;
}
complex(complex&c)//copy constructor
{
real=c.real; img=c.img;

}
complex sum(complex c )
{

complex t; t.real=real+c.real; t.img=img+c.img; return t;


}
void show()
{
If(img>0)
cout<<real<<"+i"<<img<<endl;

else

}
};

{
img=-img;
cout<<real<<"-i"<<img<<endl;
}

void main()
{
complex c1(1,2); complex c2(2,2); compex c3;
c3=c1.sum(c3); c3.show();

}
DESTRUCTOR
A destructor is a member function of the class whose name
is same as the name of the class
but the preceded with tilde sign (~). The purpose of
destructor is to destroy the object when
it is no longer needed or goes out of scope. As a very small
example of destructor see the
program given below :
/*PROG 7.25 DEMO OF DESTRUCTOR VER 1*/
#include <iostream.h>
#include <conio.h>
class demo
{
public :
demo( )
{
cout<<“Constructor called\n”;
}
~demo( )
{
cout<<“Destructor called”<<endl;
}
};
Working with Constructor and Destructor 329
void main( )
{
clrscr( );
demo d;
getch( );
}
OUTPUT :
Constructor called
Destructor called
EXPLANATION : When demo d; executes it calls the
default constructor of the class and
results in printing Constructor called. The scope of object
d is the area/place where it is
available and in the above program the scope is the whole
main function. Being the only
statement demo d; in the function main, as soon as
compiler finds ending brace of main i.e.,}
it calls destructor of the class to destroy the object d and
prints Destructor called. The code
is given as :
~demo ( )
{
cout<<”Destructor called “<<endl;
}
is a destructor of the class demo.
Features of Destructor
1. The name is same as of class but proceeded with a ~
sign.
2. Destructor is automatically called as soon as an object
goes out of scope.
3. Destructor is used to destroy the objects.
4. Once a destructor is called for a object, the object will
no longer be available for the
future reference.
5. Destructor can be used for housekeeping work such as
closing the file, de-allocating
the dynamically allocated memory etc. Closing a file in
destructor is a good idea as
user might forget to close the file associated with object.
But as the object goes out of
scope destructor will be called and all code written in
destructor executes which will
always result in closing the file and no data loss may be
there. When new is used for
allocation of memory in the constructor we must always
use delete in the destructor
to be allocate the memory.
6. Similar to constructor there is no return type for
destructor and that’s why they cannot
return any value.
7. There is no explicit or implicit category for a destructor.
They are always called
implicitly by the compiler.
8. Destructor can never take any arguments.
330 Object-Oriented Programming C++ Simplified
9. Destructor can be virtual

DESTRUCTORS:A destructor, 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.
Eg: ~item() { }
1. A destructor never takes any argument nor does it
return any value.
2. It will be invoked implicitly by the compiler upon
exit from the program to clean up storage that is no longer
accessible.
3. It is a good practice to declare destructors in a
program since it releases memory space for future use.

#include<iostream> using namespace std; class Marks


{
public:
int maths; int science;

//constructor Marks() {
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}

//Destructor

~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};

int main( )
{
Marks m1; Marks m2; return 0;
}

Output:
Inside Constructor
C++ Object created
Inside Constructor
C++ Object created
Inside Destructor
C++ Object destructed
Inside Destructor
C++ Object destructed

Anonymous Object in C++


In a C++ programming an object are created with names but It is
still possible to create object without name such object are known
as anonymous object.
When constructor and destructor are called, the data members are
initialize and destroyed respectively.

Without object we can initialize and destroy the content of the class.

All these operations are carried out without object or we can also
assume that operations are carried out using an anonymous object.

1 #include <iostream>
2
3 using namespace std;
4
5 class A {
6 public: A() // constructor
7 {
8 cout << "Constructor executed" << endl;
9 }~A() // Destructor
10 {
11 cout << "Destructor executed" << endl;
12 }
13 };
14 int main() {
15 A(); // calling constructor
16 A(); // calling constructor
17 }
Output

1 Constructor executed
2 Destructor executed
3 Constructor executed
4 Destructor executed
Note: In the above program, we have created class “A” which
contains constructor and destructor.
In the main() function, no object is created.

The constructor are called directly.

Calling constructor directly means creating anonymous object.


It is not possible to create more than one anonymous object at a
time.
When constructor execution ends , destructor is executed to
destroy the object.

You might also like