Lab 1 Q2: Writing classes and constructors

Example how to write a C++ class with constructors

For these two exercises use the Student class example given below

Exercise 1: Write a class Square which has a field for side. It must have a constructor to initialize the side.
Add methods to the Square class to calculate area and perimeter.

Exercise 2: Write a class Circle which has a field for radius. It must have a constructor to initialize the radius.
Add methods to the Circle class to calculate area and perimeter.

Student class example - shows you how to define and implement the class, it methods and constructors.

#include <iostream>
using namespace std;
 
//declaration section
class Student {
      private:
              int studentID;
              string studentName;
              int semester;
      public:          //interface
             Student();
             Student(int, string, int); //constructor                     
             void setStudentID(int);
             void setStudentName(string);
             void setSemester(int);
             void printStudentDetails();
};
 
//implementation 
Student::Student(){
}
 
Student::Student(int ID, string name, int sem) {
     studentID = ID;
     studentName = name;
     semester = sem;
}
 
void Student::setStudentID(int ID){
     studentID = ID;
}
 
void Student::setStudentName(string name){
     studentName = name;
}
 
void Student::setSemester(int sem) {
     semester = sem;
}
 
void Student::printStudentDetails() {
     cout << "ID:" << studentID << endl
          << "Name:"<< studentName << endl
          << "Semester:" << semester
          << endl;
}
 
int main() {
    //Example using default constructor
    Student s;
    s.setStudentID(10001);
    s.setStudentName("Abdullah");
    s.setSemester(3);
 
    //Example using arguments constructor 
    //Student s(1001,"Abdullah", 3);
 
    s.printStudentDetails();
 
    system("pause");
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License