Object Oriented Programming Practical 10
Question 1
WAP to implement default constructor that initializes num1 and num2 as 10 and 20 and prints the values of num1 and num2.
numbers.cpp
C
#include <iostream.h>
#include <conio.h>
class MyNumbers
{
public:
int num1;
int num2;
MyNumbers()
{
num1 = 10;
num2 = 20;
}
void show()
{
cout << "Value of num1: " << num1 << endl;
cout << "Value of num2: " << num2 << endl;
}
};
int main()
{
MyNumbers obj;
obj.show();
getch();
return 0;
}
Output

Question 2
Define a class student which contain member variables as rollno ,name and course. Write a program using constructor as "Computer Engineering" for course . Accept this data for objects of class and display the data.
student.cpp
C
#include <iostream.h>
#include <conio.h>
#include <string.h>
class Student
{
public:
int rollno;
char name[30];
char course[30];
Student()
{
strcpy(course,"Computer Engineering");
}
void acceptData()
{
cout << "Enter Roll Number: ";
cin >> rollno;
cout << "Enter Name: ";
cin>>name;
}
void displayData()
{
cout << "\n--- Student Details ---" << endl;
cout << "Roll Number: " << rollno << endl;
cout << "Name: " << name << endl;
cout << "Course: " << course << endl;
}
};
int main()
{
Student s1;
s1.acceptData();
s1.displayData();
getch();
return 0;
}
Output

Question 3
WAP to declare a class student having datamembers as name and percentage .Write constructor to initialise these data members. Accept and display data for one object.
student1.cpp
C
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Student
{
private:
char name[50];
float percentage;
public:
Student(char n[50], float p)
{
strcpy(name,n);
percentage=p;
}
void display()
{
cout << "Name: " << name << endl;
cout << "Percentage: " << percentage << endl;
}
};
int main()
{
string sname;
float spercent;
cout << "Enter student's name: ";
getline(cin, sname);
cout << "Enter student's percentage: ";
cin >> spercent;
Student s(sname, spercent);
cout << "\nStudent Details:\n";
s.display();
getch();
return 0;
}
Output

Question 4
WAP to declare class time having data members as hrs, min,sec. Write a constructor to accept data and display for two objects.
time.cpp
C
#include<iostream.h>
#include<conio.h>
class time
{
int hour,mins,sec;
public:
time(int h,int m,int s)
{
hour=h;
mins=m;
sec=s;
}
void display()
{
cout<<hour<<":"<<mins<<":"<<sec;
}
};
int main()
{
clrscr();
int hh,mm,ss;
cout<<"\nEnter time 1:"<<endl;
cout<<"Enter hour: ";
cin>>hh;
cout<<"Enter minutes: ";
cin>>mm;
cout<<"Enter seconds: ";
cin>>ss;
time t1(hh,mm,ss);
cout<<"\nEnter time 2:"<<endl;
cout<<"Enter hour: ";
cin>>hh;
cout<<"Enter minutes: ";
cin>>mm;
cout<<"Enter seconds: ";
cin>>ss;
time t2(hh,mm,ss);
cout<<"\nTime 1 is: ";
t1.display();
cout<<"\nTime 2 is: ";
t2.display();
getch();
return 0;
}
Output
