c++ programming questions with solutions

  1) Explain the concept of copy constructor with the help of an example program
   
#include<iostream>
#include<string.h>
using namespace std;
class student
{
char *name;
int roll;
public:
    student()
    {
    name = " ";
    roll = 0;
}
student(char *n, int r)
{
name = n;
roll = r;
}
student(student &s)
{
strcpy(name, s.name);
roll = s.roll;
}
void dis()
{
cout<<"name = "<<name<<endl;
cout<<"roll = "<<roll<<endl;
}
};
int main()
{
student s1("asdsa",25), s2;
s2.dis();
s2 = s1;
s2.dis();
return 1;
}

  2) What is function template ? Write a function template SUM to add two numbers.


#include<iostream>
using namespace std;
template<class T>
T SUM(T v1,T v2)
{
T x = v1+v2;
return x;
}
float add(int x, int y)
{
return(x+y);
}
int main()
{
float x=5.2, y=6.5;
cout<<"x = "<<x<<endl<<"y = "<<y<<endl<<"x + y = "<<SUM(x,y)<<endl;
cout<<"x = "<<x<<endl<<"y = "<<y<<endl<<"x + y = "<<add(x,y);
return 1;
}


  3)Write a program in C++, which take two 3 x 3 matrices as input and find sum of  them. Implement suitable constructor and destructor for this program.

  4)Explain need of operator overloading. Also explain why some operators can not be overloaded? Write a C++ program to overload '+' operator to add two character strings.

  5)What is exception ? Explain how exception  handling is done in C++ with the help of a 
program. Also describe what will happen if an exception is thrown out side of a try block and why ?


No comments:

Post a Comment