C++ Programming
Slip14
Q.1) Write a C++ program to create a class Book which contains data members as B_Id,
B_Name, B_Author, B_Publication. Write member functions to accept and display Book
information also display Count of books. (Use Static data member to maintain Count of
books) [Marks 15]
Solution
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class book
{
private:
int bid;
char bname[20];
char bauthor[20];
char bpubl[20];
static int cnt;
public:
book()
{
cnt++;
}
void accept()
{
cout<<"Enter the book id:";
cin>>bid;
cout<<"Enter the book bname:";
gets(bname);
cout<<"Enter the book author:";
gets(bauthor);
cout<<"Enter the book publisher:";
gets(bpubl);
}
void display()
{
cout<<"\nBOOK ID IS: "<<bid;
cout<<"\nBOOK NAME IS: "<<bname;
cout<<"\nBOOK AUTHOR IS: "<<bauthor;
cout<<"\nBOOK PUBLICATION IS: "<<bpubl;
}
static void count()
{
cout<<"\nCount ="<<cnt;
}
};
int book:: cnt=0;
void main()
{
book b1,b2;
clrscr();
b1.accept();
b2.accept();
b1.display();
b2.display();
book::count();
getch();
}
Output
Enter the book id:123
Enter the book bname:half girlfriend
Enter the book author:cetan bhagat
Enter the book publisher:abc
Enter the book id:321
Enter the book bname:two status
Enter the book author:chetan bhagat
Enter the book publisher:xyz
BOOK ID IS: 123
BOOK NAME IS: half girlfriend
BOOK AUTHOR IS: cetan bhagat
BOOK PUBLICATION IS: abc
BOOK ID IS: 321
BOOK NAME IS: two status
BOOK AUTHOR IS: chetan bhagat
BOOK PUBLICATION IS: xyz
Count =2
Q.2) Create a base class Shape. Derive three different classes Circle, Rectangle and Triangle
from Shape class. Write a C++ program to calculate area of Circle, Rectangle and
Triangle. (Use pure virtual function). [Marks 25]
Solution
#include<iostream.h>
#include<conio.h>
class shape
{
public:
virtual void area()=0;
virtual void accept()=0;
};
class circle:public shape
{
int r;
public:
void accept()
{
cout<<"\n Enter radious";
cin>>r;
}
void area()
{
cout<<"\n Area of circle is "<<3.14*r*r;
}
};
class rectangle:public shape
{
int l,b;
public:
void accept()
{
cout<<"\n Enter length & breadth";
cin>>l>>b;
}
void area()
{
cout<<"\n Area of rectangle is :-"<<l*b;
}
};
class trangle:public shape
{
int l,b;
public:
void accept()
{
cout<<"\n Enter length and breadth";
cin>>l>>b;
}
void area()
{
cout<<"\n Area of trangle is:- "<<0.5*l*b;
}
};
void main()
{
shape *j;
rectangle r;
circle c;
trangle t;
clrscr();
j=&r;
j->accept();
j->area();
j=&c;
j->accept();
j->area();
j=&t;
j->accept();
j->area();
getch();
}
Output
Enter length & breadth
5
6
Area of rectangle is :-30
Enter radious5
Area of circle is 78.5
Enter length and breadth10
20
Area of trangle is:- 100
Tags:
c++