CS 304-Assignment 1
CS 304-Assignment 1 |
Note:
Submit your file in .cpp format.remove comments in code. write your own id in code.
Solution:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
int studentId;
public:
// Default constructor
Student() {
name = "";
age = 0;
studentId = 0;
}
// Parameterized constructor
Student(string newName, int newAge, int newStudentId) {
name = newName;
age = newAge;
studentId = newStudentId;
}
// Copy constructor (shallow copy)
Student(const Student& other) {
name = other.name;
age = other.age;
studentId = other.studentId;
}
// Assignment operator (deep copy)
Student& operator=(const Student& other) {
if (this != &other) {
name = other.name;
age = other.age;
studentId = other.studentId;
}
return *this;
}
// Getter methods
string getName() const {
return name;
}
int getAge() const {
return age;
}
int getStudentId() const {
return studentId;
}
// Setter methods
void setName(string newName) {
name = newName;
}
void setAge(int newAge) {
age = newAge;
}
void setStudentId(int newStudentId) {
studentId = newStudentId;
}
// Print method to display student info
void printInfo() const {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Student ID: " << studentId << endl;
}
};
int main() {
// Creates s1 using parameterized constructor
Student s1("John Doe", 20, 12345);
// Creates s2 using copy constructor
Student s2 = s1;
// Creates s3 using assignment operator
Student s3;
s3 = s1;
// Prints all three Student objects
cout << "Student 1: " << endl;
s1.printInfo();
cout << endl;
cout << "Student 2: " << endl;
s2.printInfo();
cout << endl;
cout << "Student 3: " << endl;
s3.printInfo();
cout << endl;
// Modifies name of s1
s1.setName("Jane Smith");
// Prints all three Student objects after modifying s1's name
cout << "Student 1: " << endl;
s1.printInfo();
cout << endl;
cout << "Student 2: " << endl;
s2.printInfo();
cout << endl;
cout << "Student 3: " << endl;
s3.printInfo();
cout << endl;
return 0;
}
0 Comments