Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Practical 1: Classes and Methods

Q.1 Design an employee class for reading and displaying the employee
information, the getInfo() and displayInfo() methods will be used
respectively where getinfo() will be private method.
Code:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Employee
{
private:
char name[50];
int age;
double salary;

void getInfo()
{
clrscr();

cout << "Enter Employee Name: ";


gets(name);
cout << "Enter Employee Age: ";
cin >> age;

cout << "Enter Employee Salary: ";


cin >> salary;
}

public:
void displayInfo()
{
getInfo();
clrscr();
cout << "\nEmployee information:\n";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Salary: $" << salary << endl;

getch();
}
};

void main()
{
Employee emp;
emp.displayInfo();
getch();
}

Q.2 Design the class student containing getData() and displayData() as


two of its methods which will be used for reading and displaying the
student information respectively. Where getData() will be private
method.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Student
{
private:
char name[50];
int age;
double grade;

void getInfo()
{
clrscr();

cout << "Enter Student Name: ";


gets(name);

cout << "Enter Student Age: ";


cin >> age;

cout << "Enter Student Grade: ";


cin >> grade;
}

public:
void displayInfo()
{
getInfo();
clrscr();
cout << "\nEmployee information:\n";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Grade: " << grade << endl;

getch();
}
};

void main()
{
Student student;
student.displayInfo();
getch();
}
Q.3 Design the class Demo which will contain the following methods:
readNo(), factorial() for calculating the factorial of a number,
reverseNo() will reverse the given number, isPalindrome() will check
the given number is palindrome, isArmstrong() which will calculate
the given number is armStrong or not.Where readNo() will be private
method.

Q.4 Write a program to demonstrate function definition outside class


and accessing class members in function definition
#include <iostream.h>
#include <stdio.h>
#include <conio.h>

class MyClass
{
private:
int privateVar;

public:
// Constructor
MyClass()
{
privateVar = 0;
}
// Member function declaration
void setPrivateVar(int value);

void displayPrivateVar();
};

// Member function definition outside the class


void MyClass::setPrivateVar(int value)
{
privateVar = value;
}

void MyClass::displayPrivateVar()
{
cout << "Private Variable: " << privateVar << endl;
}

int main()
{
// Create an instance of the MyClass
MyClass myObject;
// Access class members using member functions
myObject.setPrivateVar(42);
myObject.displayPrivateVar();

getch(); // Wait for a key press


return 0;
}

You might also like