Fall 2023 - CS304 - 2

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

Sample solution of Assignment 2

#include <iostream>
#include <string>

class Base {
public:
virtual void display() const = 0; // Pure virtual function
};

class child1 : public Base {


public:
void display() const override {
std::cout << "---------------" << std::endl;
std::cout << "Student Name: Muhammad Shehryar " << studentName << std::endl;
}

private:
std::string studentName;
};

class child2 : public Base {


public:
void display() const override {
std::cout << "________________" << std::endl;
std::cout << "I am enrolled in Course: CS304 " << course << std::endl;
std::cout << "---------------" << std::endl;
}

private:
std::string course;
};

void showID(const int* idArray, int size) {


std::cout << "Student ID: ";

for (int i = 0; i < size; ++i) {


std::cout << idArray[i];

}
std::cout << std::endl;
std::cout << "---------------" << std::endl;
}
void sumLastThreeDigits(const int* idArray, int size) {
if (size < 3) {
std::cout << "Cannot calculate the sum of the last three digits." << std::endl;
return;
}

int sum = idArray[size - 3] + idArray[size - 2] + idArray[size - 1];


std::cout << "Sum of the last three digits: " << sum << std::endl;
}

int main() {
int studentIDArray[] = {2, 1, 0, 4, 1, 4, 6, 0, 4};
int arraySize = sizeof(studentIDArray) / sizeof(studentIDArray[0]);

child1 d1;
child2 d2;

Base* p;

std::string S1 = "Muhammad Shehryar";


std::string S2 = "CS304";

// Assign the object of child1 class to the pointer p and display


p = &d1;
d1.display();

// Assign the object of child2 class to the pointer p and display


p = &d2;
d2.display();

// Call showID function


showID(studentIDArray, arraySize);
// Call sumLastThreeDigits function
sumLastThreeDigits(studentIDArray, arraySize);

return 0;
}

You might also like