0% found this document useful (0 votes)
515 views38 pages

C++ Function Overloading & Classes Guide

The document discusses implementing function overloading with default arguments in C++. It defines three functions called repchar() that are overloaded - one takes no arguments, one takes a character argument, and one takes a character and integer argument. It demonstrates calling each overloaded function and shows the output is printed correctly based on the arguments passed.

Uploaded by

shiva1990
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
515 views38 pages

C++ Function Overloading & Classes Guide

The document discusses implementing function overloading with default arguments in C++. It defines three functions called repchar() that are overloaded - one takes no arguments, one takes a character argument, and one takes a character and integer argument. It demonstrates calling each overloaded function and shows the output is printed correctly based on the arguments passed.

Uploaded by

shiva1990
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Function overloading with default arguments

Ex.No:1
Date:
AIM:
To Implement a Function overloading with default arguments in C++
PROGRAM:

//demonstrates function overloading&default argument


#include<iostream.h>
#include<conio.h>
void repchar();
void repchar(char);
void repchar(char,int);
void main()
{
getch();
clrscr();
repchar();
repchar('=');
repchar('+',30);
}
//repchar()
//display 45 asterisks
void repchar()
{
for(int j=0;j<45;j++)
cout<<'*';
cout<<endl;
}
//repchar()
//display 45 copies of special characters
void repchar(char ch)
{
for(int j=0;j<45;j++)
cout<<ch;
cout<<endl;
}
//repchar()
//display specified number of copies of specified characters
void repchar(char ch,int n)
{
for(int j=0;j<n;j++)
cout<<ch;
cout<<endl;
}

output

*********************************************
=============================================
++++++++++++++++++++++++++++++

RESULT:
Thus the program to Implement a Function overloading, default arguments
using C++ was Executed Successfully
----------------------------
Define Simple class with name space
Ex.No:2
Date:
AIM:
To implement a Simple class design with namespaces and objects creations
usingC++
PROGRAM:

#include<iostream>
#include<conio.h>
using namespace std;
namespace mylib{
class student
{
char *name;
int roll;
public:
student(char *tname , int troll)
{
name = tname;
roll=troll;
}
void Disp()
{
cout<<name<<roll;
}
};
}
using namespace mylib;
int main()
{
mylib::student s("rohit", 234);
s.Disp();
getch();
return 0;
}

output

RESULT:
Thus the program to implement a Simple class design with namespaces and
objects creations using C++ was executed successfully.
________________________________________________________________

Constructor ,Destructor and Dynamic memory allocation


Ex.No:3
Date:
AIM:
To implement Dynamic memory allocation with destructor and copy constructor
usingC++
PROGRAM:
#include<iostream>
#include<conio.h>
//using namespace std;
class STUDENT
{
int age;
int rollno;
float perc;
public:
int input();
int output();
STUDENT()
{
cout<<endl<<"Constructor 1"<<endl;
perc=0;
rollno=0;
age=0;

}
STUDENT(int roll)
{
cout<<endl<<"Constructor 2"<<endl;
rollno=roll;
age=0;perc=0;
}
STUDENT(int roll, int AGE)
{
cout<<endl<<"Constructor 3"<<endl;
rollno=roll;
age=AGE;
perc=0;
}
STUDENT(int roll,float PERC)
{
cout<<endl<<"Constructor 4"<<endl;
rollno=roll;
age=0;
perc=PERC;
}
~STUDENT()
{
cout<<endl<<"destructor at work\t"
<<"roll no : "<<rollno<<endl;
}
};
int STUDENT::input()
{
cout<<endl;
cout<< "Enter Roll number :: ";
cin>>rollno;
cout<<"ENter perc :: ";
cin>>perc;
cout<<"ENter age :: ";
cin>>age;
return 1;
}
int STUDENT::output()
{
cout<<endl;
cout<<endl<<"Roll number\t::\t"<<rollno;
cout<<endl<<"Age\t\t::\t"<<age;
cout<<endl<<"Perc. \t\t::\t"<<perc;
return 1;
}

int main()
{
getch();
clrscr();
STUDENT a=STUDENT();
STUDENT b(12);
STUDENT c(13,66);
STUDENT d(14,5.66F);
STUDENT *e;
e=new STUDENT(34,6);
a.output();
b.output();
c.output();
d.output();
e->output();
cout<<"\ndeleting e"<<endl;
delete(e);
cout<<endl<<"e deleted"<<endl;
return 1;
}
OUTPUT
Constructor 1
Constructor 2
Constructor 3
Constructor 4
Constructor 3

Roll number :: 0
Age :: 0
Perc. :: 0

Roll number :: 12
Age :: 0
Perc. :: 0

Roll number :: 13
Age :: 66
Perc. :: 0

Roll number :: 14
Age :: 0
Perc. :: 5.66

Roll number :: 34
Age :: 6
Perc. :: 0
deleting e

destructor at work roll no : 34


e deleted
destructor at work roll no : 14
destructor at work roll no : 13
destructor at work roll no : 12
destructor at work roll no : 0
Process returned 1 (0x1) execution time : 0.094 s
Press any key to continue.

RESULT:
Thus the program to implement the constructor,destructor and Dynamic memory
allocation using C++ was executed successfully.
________________________________________________________________
CopyConstructor and Overloading assignment operator
Ex.No:4
Date:

AIM:
To implement CopyConstructor and Overloading assignment operator usingC+
+

PROGRAM:
#include <iostream.h>
#include<conio.h>
//using namespace std;
class MyClass
{
private:
int data;

public:
MyClass(){ }
MyClass(int d){ data = d; }
MyClass(MyClass& a){
data = a.data;
cout << "\nCopy constructor invoked";
}
void display(){ cout << data; }
void operator = (MyClass& a)
{
data = a.data;
cout << "\nAssignment operator invoked";
}
};
int main()
{ getch();
clrscr();
MyClass a1(37);
MyClass a2;

a2 = a1;
cout << "\na2="; a2.display();

MyClass a3(a1);

cout << "\na3="; a3.display();


return 0;
}

output
Assignment operator invoked
a2=37
Copy constructor invoked
a3=37

RESULT:
Thus the program to implement Copy Constructor and Overloading assignment
operator using C++ was executed successfully.

Operator overloading using friend function

Ex.No:5
Date:
AIM:
To implement Operator overloading using friend function in c++

PROGRAM:

//using friend function to


//overload addition and subtraction operators
#include<iostream.h>
#include<conio.h>
class myclass
{
int a;
int b;
public:
myclass(){}
myclass(int x,int y)
{
a=x;
b=y;
}
void show()
{
cout<<a<<endl;
cout<<b<<endl;
}
friend myclass operator+(myclass,myclass);
friend myclass operator-(myclass,myclass);
};
myclass operator+(myclass ob1,myclass ob2)
{
myclass temp;
temp.a=ob1.a+ob2.a;
temp.b=ob1.b+ob2.b;
return temp;
}

myclass operator-(myclass ob1,myclass ob2)


{
myclass temp;
temp.a=ob1.a-ob2.a;
temp.b=ob1.b-ob2.b;
return temp;
}

void main()
{
getch();
clrscr();
myclass a(10,20);
myclass b(100,200);
a=a+b;
a.show();
}
Output

110
220

RESULT:
Thus the program to implement Operator overloading with friend function
using C++ was executed successfully

Type Conversion(Convert class type to Basic type)

Ex.No:6
Date:
AIM:
To implement Type Conversion concept in c++

PROGRAM:
#include <iostream.h>
#include <string.h>
#include<conio.h>
//using namespace std;

class StringClass {
char str[80];
int len;
public:
StringClass(char *s) {
strcpy(str, s);
len = strlen(s);
}
operator char *() {
return str;
}
operator int() {
return len;
}
};

int main()
{
getch();
clrscr();
StringClass s("Conversion functions are convenient.");
char *p;
int l;

l = s; // convert s to integer - which is length of string


p = s; // convert s to char * - which is pointer to string

cout << "The string:\n";


cout << p << "\nis " << l << " chars long.\n";
return 0;
}

output
The string:
Conversion functions are convenient.
is 36 chars long.

RESULT:
Thus the program to implement “Convert class type to Basic Datatype”
using C++ was executed successfully

Inheritance( Hybrid Inheritance)

Ex.No:7(a)
Date:
AIM:
To implement the Inheritance concept in c++
PROGRAM:
#include <iostream.h>
class mm
{
protected:
int rollno;
public:
void get_num(int a)
{ rollno = a; }
void put_num()
{ cout << "Roll Number Is:"<< rollno << "\n"; }
};
class marks : public mm
{
protected:
int sub1;
int sub2;
public:
void get_marks(int x,int y)
{
sub1 = x;
sub2 = y;
}
void put_marks(void)
{
cout << "Subject 1:" << sub1 << "\n";
cout << "Subject 2:" << sub2 << "\n";
}
};

class extra
{
protected:
float e;
public:
void get_extra(float s)
{e=s;}
void put_extra(void)
{ cout << "Extra Score::" << e << "\n";}
};

class res : public marks, public extra{


protected:
float tot;
public:
void disp(void)
{
tot = sub1+sub2+e;
put_num();
put_marks();
put_extra();
cout << "Total:"<< tot;
}
};

int main()
{
res std1;
std1.get_num(10);
std1.get_marks(10,20);
std1.get_extra(33.12);
std1.disp();
return 0;
}

Result:
Roll Number Is: 10
Subject 1: 10
Subject 2: 20
Extra score:33.12
Total: 63.12

RESULT:
Thus the program to implement Inheritance concept using C++ was executed
successfully.

Dynamic Memory Allocation (or) run-time polymorphism

Ex.No:7(b)
Date:
AIM:
To implement the Inheritance concept with run-time polymorphism
PROGRAM:
#include <iostream.h>
#include<conio.h>
//using namespace std;

class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
void printarea (void)
{ cout << this->area() << endl; }
};
class CRectangle: public CPolygon {
public:
int area (void)
{ return (width * height); }
};

class CTriangle: public CPolygon {


public:
int area (void)
{ return (width * height / 2); }
};

int main ()
{
getch();
clrscr();
CPolygon * ppoly1 = new CRectangle;
CPolygon * ppoly2 = new CTriangle;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly1->printarea();
ppoly2->printarea();
delete ppoly1;
delete ppoly2;
return 0;
}

output
20
10

RESULT:
Thus the program to implement Inheritance concept with run-time polymorphism
using C++ was executed successfully.

Template design in C++


Ex.No:8
Date:
AIM:
To implement Templet design using c++
PROGRAM:
#include <iostream.h>

template <class T>
class MyClass {
    T value1, value2;
  public:
    MyClass (T first, T second){
        value1=first; 
        value2=second;
    }
    T getmax ()
    {
      T retval;
      retval = value1>value2 ? value1 : value2;
      return retval;
    }
    
};

int main () {
  MyClass <int> myobject (100, 75);
  
  cout << myobject.getmax();
  
  return 0;
}

output

100

RESULT:
Thus the program to design a templet using C++ was executed successfully.
Input and OutPut Throwing Exception and Catching exceptions in C++

Ex.No:9
Date:
AIM:
To implement Input and OutPut Throwing Exception and Catching exceptions
in c++
PROGRAM:
#include <iostream.h>
int main()
{
int x,y;
cout << "Enter values of x::";
cin >> x;
cout << "Enter values of y::";
cin >> y;
int r=x-y;
try
{
if ( r!=0)
{
cout << "Result of division is x/r:: " << x/r <<
"\n";
}
else
{
throw ( r);
}
}
catch( int r)
{
cout << "Division by zero exception::
value of r is::" << r << "\n";
}
cout << "END";
return 0;
}

Result:
Enter values of x::12
Enter values of y::12
Division by zero exception::value of r is::0
RESULT:
Thus the program to implement the Input and Output Throwing Exception and
Catching exceptions using C++ was executed successfully.
Standard Template Library
Ex.No:10
Date:
AIM:
To develop Standard Template Library in c++
PROGRAM:
// mathfunc.cpp
// compile with: /EHsc
//
// Structures: plus<A> - Adds data type A object to
// a class object derived from plus.
// minus<A> - Subtracts data type A.
// multiplies<A> - Multiplies object by data type A.
// divides<A> - Divides object by data type A.
// modulus<A> - Returns object modulo A.

#include <functional>
#include <iostream>
#include<conio.h>

using namespace std ;

class MathOps : public plus<int>, public minus<int>,


public multiplies<int>, public divides<int>,
public modulus<int>
{
public:
int value;
MathOps(){value=0;}
MathOps(int x){value=x;}
result_type operator+(second_argument_type add2)
{return value + add2;}
result_type operator-(second_argument_type sub2)
{return value - sub2;}
result_type operator*(second_argument_type mult2)
{return value * mult2;}
result_type operator/(second_argument_type div2)
{return value / div2;}
result_type operator%(second_argument_type mod2)
{return value % mod2;}
friend ostream& operator<<(ostream& os, const MathOps& obj ) ;
};
ostream& operator<<(ostream& os, const MathOps& obj )
{
os << obj.value ;
return os ;
}
int main(void)
{
//getch();
MathOps one,two,three,four,five,six;
cout << "Using MathOps class..." << endl ;
one = 18;

cout << "one = " << one << endl ;


two = one + 1;
cout << "two = one + 1 = " << two << endl ;
three = two - 2;
cout << "three = two - 2 = " << three << endl ;
four = three * 3;
cout << "four = three * 3 = " << four << endl ;
five = four / 4;
cout << "five = four / 4 = " << five << endl ;
six = five % 5;
cout << "six = five % 5 = " << six << endl ;
getch();
}
output
RESULT:
Thus the program to develop the STL using C++ was executed successfully.
Simple class designs in Java with Javadoc
Ex.No:11
Date:
AIM:
To implement Simple class designs with Javadoc using Java language.
PROGRAM:
Program for javaDoc

/**
* This immutable class represents <i>complex
* numbers</i>.
*
* @author David Flanagan
* @version 1.0
*/
public class Complex {
/**
* Holds the real part of this complex number.
* @see #y
*/
protected double x;

/**
* Holds the imaginary part of this complex number.
* @see #x
*/
protected double y;
/**
* Holds the constant values
* @see #x
* @see #y
*/
private final double z;

/**
* Creates a new Complex object that represents the complex number
* x+yi.
* @param x The real part of the complex number.
* @param y The imaginary part of the complex number.
* @return complex
*/
public Complex(double x, double y) {
this.x = x;
this.y = y;
}

/**
* Adds two Complex objects and produces a third object that represents
* their sum. * @param c1 A Complex object
* @param c2 Another Complex object
* @return A new Complex object that represents the sum of
* <code>c1</code> and
* <code>c2</code>.
* @exception java.lang.NullPointerException
* If either argument is null
*/
public Complex add(Complex c1, Complex c2) {
return new Complex(c1.x + c2.x, c1.y + c2.y);
}
/**
* @deprecated As of release 1.3, replaced by {@link #getPreferredSize()}
*/
@Deprecated public Dimension preferredSize() {
return getPreferredSize();
}
}

output

Package 
 Class  Tree  Depr Index  Help 
ecat
ed 
 PREV CLASS   NEXT CLASS FRAMES    NO FRAMES     All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Class Complex
java.lang.Object
Complex

public class Complex


extends java.lang.Object

This immutable class represents complex numbers.


Field Summary
protected x
double           Holds the real part of this complex number.
protected y
double           Holds the imaginary part of this complex number.

Constructor Summary
Complex(double x, double y)
          Creates a new Complex object that represents the complex number x+yi.

Method Summary
 Complex add(Complex c1, Complex c2)
          Adds two Complex objects and produces a third object that
represents their sum.
 Dimension preferredSize()
          Deprecated. As of release 1.3, replaced by #getPreferredSize()

Methods inherited from class java.lang.Object


clone, equals, finalize, getClass, hashCode, notify, notifyAll,
toString, wait, wait, wait

Field Detail
x
protected double x
Holds the real part of this complex number.
See Also:
y

y
protected double y
Holds the imaginary part of this complex number.
See Also:
x

Constructor Detail
Complex
public Complex(double x,
double y)
Creates a new Complex object that represents the complex number x+yi.
Parameters:
x - The real part of the complex number.
y - The imaginary part of the complex number.

Method Detail
add
public Complex add(Complex c1,
Complex c2)
Adds two Complex objects and produces a third object that represents their sum. *
@param c1 A Complex object
Parameters:
c2 - Another Complex object
Returns:
A new Complex object that represents the sum of c1 and c2.
Throws:
java.lang.NullPointerException - If either argument is null

preferredSize
@Deprecated
public Dimension preferredSize()
Deprecated. As of release 1.3, replaced by #getPreferredSize()

Package 
 Class  Tree  Depr Index  Help 
ecat
ed 
 PREV CLASS   NEXT CLASS FRAMES    NO FRAMES     All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
RESULT:
Thus the program to implement Simple class designs with Javadoc using Java
was executed successfully.

Designing Packages with Javadoc comments


Ex.No:12
Date:
AIM:
To implement Packages with Javadoc comments using Java
PROGRAM:
package pack1;

public class SampleA


{
public void get()
{
System.out.println("This is a Sample A Package");
}
}
………………………………………………………………………..
import pack1.*;
//package pack2;

public class SampleA1


{
protected double a=20;
public double area1()
{
double c=a+a;
System.out.println(c);
return c;
}
public static void main(String args[])
{
SampleA a=new SampleA();
SampleA1 a1=new SampleA1();
a.get();
a1.area1();
}
}
RESULT:
Thus the program to implement Packages with Javadoc comments using Java
was executed successfully.
Interfaces Concept in Java
Ex.No:13(a)
Date:
AIM:
To implement Interfaces in Java
PROGRAM:
interface inter1{
void getName();
}
interface inter2{
void getAge();
}
interface myinterface extends inter1, inter2{
void getCompany();
}
class interdemo implements myinterface{
public void getName(){System.out.println ("Ravindran");}
public void getAge() { System.out.println("55");}
public void getCompany() { System.out.println("TamilNadu Electricity Board");}
public static void main(String args[]){
interdemo I = new interdemo();
I. getName();
I. getAge();
I. getCompany();
}
}
output

RESULT:
Thus the program to implement Interfaces Concept using Java
was executed successfully.
_____________________________________________________________
Inheritance Concept in Java
Ex.No:13(b)
Date:
AIM:
To implement Inheritance in Java
PROGRAM:
class base
{
double a=10,b=20;
void cal()
{
System.out.println("The total Values :"+(a+b));
}

}
class sub extends base
{
double calc(double x,double y)
{
return x*y;
}

}
class sub1 extends sub
{
sub1()
{
System.out.println("This is Sub1 class");
}
sub1(int a)
{
System.out.println("A value si:"+a);
}
}
class DemoInherit
{
public static void main(String[] r)
{
sub1 s=new sub1();
s.cal();
System.out.println(" Mul res:"+s.calc(5.0,6.0));
new sub1();
new sub1(10);
}
}
output

RESULT:
Thus the program to implement Inheritance Concept using Java
was executed successfully.
_____________________________________________________________
Exceptions Handling in Java(ArithmeticException)
Ex.No:14(a)
Date:
AIM:
To implement Exceptions handling in Java

PROGRAM:
/*prgm to illustrate resuming of execution after error reporting */

class errorrepo
{
public static void main(String args[])
{
int a=10,b=5,c=5,x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Error in denominator value check ");
}
y=a/(b+c);
System.out.println("value of y = "+y);
}
}

output

RESULT:
Thus the program to implement Exceptions handling using Java
was executed successfully.
_____________________________________________________________
Exceptions Handling (ArrayIndexOutofBoundException)
Ex.No:14(b)
Date:
AIM:
To implement Exceptions handling in Java
PROGRAM:
class exec
{
public static void main(String arg[])
{
try
{
int a,b,c;
a=45;b=0;
c=a/b;
int d[]={1};
d[7]=89;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
catch(Exception e){
System.out.println(e);}
}
}
output

RESULT:
Thus the program to implement Exceptions handling using Java
was executed successfully.
INPUT AND OUTPUT OPERATION
Ex.No:15
Date:
AIM:
To implement input and output operation in Java

PROGRAM:

import java.io.*;
class ioexample
{
public static void main(String[] args)
{
try {
File ip = new File("input.txt");
File op = new File("output.txt");
FileInputStream fis = new
FileInputStream(ip);
FileOutputStream fos = new
FileOutputStream(op);
int i;
while ((i = fis.read()) != -1)
{
fos.write(i);
}
fis.close();
fos.close();
}
catch (FileNotFoundException fnfe)
{
System.err.println("FileStreamsTest: " +
fnfe);
}
catch (IOException ioe)
{
System.err.println("FileStreamsTest: " + ioe);
} }}
output

input.txt

output.txt

RESULT:
Thus the program to implement input and output operation using Java
was executed successfully.
MultiThreaded Program
Ex.No:16
Date:
AIM:
To implement MultiThreaded Program in Java

PROGRAM:
// Create multiple threads.
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run()
{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(2000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

output
RESULT:
Thus the program to implement MultiThreaded Program using Java
was executed successfully.

You might also like