Assignment.docx
Assignment.docx
class Temperature {
private:
double celsius;
double fahrenheit;
double toFahrenheit(double c) {
return (c * 9.0 / 5.0) + 32;
}
double toCelsius(double f) {
return (f - 32) * 5.0 / 9.0;
}
public:
Temperature(double temp, bool isCelsius = true) {
if (isCelsius) {
celsius = temp;
fahrenheit = toFahrenheit(temp);
} else {
fahrenheit = temp;
celsius = toCelsius(temp);
}
}
void setCelsius(double temp) {
celsius = temp;
fahrenheit = toFahrenheit(temp);
}
int main() {
Temperature temp1(25); // 25°C
std::cout << "Temperature: " << temp1.getCelsius() << "°C = " << temp1.getFahrenheit()
<< "°F" << std::endl;
class Student {
private:
char name[50];
int marks1;
int marks2;
public:
void input() {
std::cout << "Enter student name: ";
std::cin.getline(name, 50);
std::cout << "Enter marks1: ";
std::cin >> marks1;
std::cout << "Enter marks2: ";
std::cin >> marks2;
}
int main() {
Student s;
std::cin.ignore();
s.input();
s.disp();
return 0;
}
Ans3: A class in C++ is a blueprint or template for creating objects. It defines data
members (variables) and member functions (methods) that operate on the data. A class
encapsulates data and behavior, supporting object-oriented programming (OOP).
An object is an instance of a class. When you create an object, it gets its own copy of the
data members and can use the class's methods.
You can access the members of a class using the dot (.) operator for an object.
class Student {
private:
std::string name;
int rollNumber;
double marks;
public:
Student(std::string studentName, int studentRollNumber, double studentMarks) {
name = studentName;
rollNumber = studentRollNumber;
marks = studentMarks;
}
~Student() {
std::cout << "Student object destroyed for " << name << std::endl;
}
int main() {
Student s("John Doe", 101, 85.5);
s.displayDetails();
return 0;
}
class Distance {
private:
int meters;
public:
Distance(int m = 0) : meters(m) {}
int main() {
Distance d1(50), d2(30);
Distance d3 = addDistance(d1, d2);