C++ Programming
Slip23
Q.1) Write the definition for a class called ‘ point’ that has x & y as integer data members.
Use copy constructor to copy one object to another. (Use Default and parameterized
constructor to initialize the appropriate objects)
Write a C++ program to illustrate the use of above class. [Marks 15]
Solution
#include<iostream.h>
#include<conio.h>
class point
{
int x,y;
public:
point()
{
x=0;
y=0;
}
point(int n,int m)
{
x=n;
y=m;
}
point(point &p)
{
x=p.x;
y=p.y;
}
void display()
{
cout<<"Numbers are: "<<endl;
cout<<x<<"\t"<<y<<endl;
}
};
int main()
{
clrscr();
point no1(10,30);
point no2(no1);
cout<<"First Object... \n";
no1.display();
cout<<"Second Object... \n";
no2.display();
getch();
return 0;
}
Output
First Object...
Numbers are:
10 30
Second Object...
Numbers are:
10 30
Q.2) Create a C++ class MyFile containing:
- FILE *fp;
- Char filename[maxsize];
Write necessary member Functions using operator overloading:
<< To display the contents of a file
>> To write the contents into a file [Marks 25]
Solution
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<string.h>
class MyFile
{
char *filename;
FILE *fp;
public:
MyFile(char *fname)
{
filename = new char[strlen(fname) + 1];
strcpy(filename,fname);
}
friend void operator>>(istream &,MyFile);
friend void operator<<(ostream &,MyFile);
};
void operator>>(istream &din,MyFile obj)
{
char ch;
obj.fp = fopen(obj.filename, "r");
if(obj.fp == NULL)
{
cout<<"\n\t Error in openning file";
getch();
}
cout<<"\n\tContents of file:";
while(feof(obj.fp) == 0)
{
ch = fgetc(obj.fp);
cout<<ch;
}
fclose(obj.fp);
}
void operator<<(ostream &dout,MyFile obj)
{
obj.fp = fopen(obj.filename, "w");
char buff[100];
cout<<"\n\t Enter content to write in file:";
fflush(stdin); gets(buff);
for(int i=0;buff[i] != '\0' ; i++)
fputc(buff[i],obj.fp);
dout<<"\n\t Contents are written in file successfully";
fclose(obj.fp);
}
int main()
{
MyFile obj("D:/sy2014/cpp/test.txt");
cout<<obj;
cin>>obj;
getch();
return 0;
}
Tags:
c++