1
Program 1
Aim (Write on the ruler page)
Write a program in C++ using virtual function. The program must declare p to be a pointer to objects of the base class person First, the program must assign p to point an instance x (name of the person e.g. “BOB”) of class person. The program must then assign p to point at an instance y (name of student, e.g. “TOM”) of the derived class student. Define a print () function in the base class such that it invokes the same base class function to print the name of the person by default. The second call for the same should evoke the derived class the name of the student
Program (Start from new page after AIM)
#include<iostream.h>
#include<string.h>
#include<conio.h>
class person {
public:
person(char* s) {
name = new char[strlen(s )+ 1];
strcpy(name, s);
}
virtual void print() {
cout << "My name is " << name;
}
protected:
char* name;
};
class student : public person {
float rno;
public:
student(char* s, float r) : person(s), rno(r) {}
void print() {
cout << "My name is " << name << " and my roll number is " << rno;
}
};
void main() {
person* p;
person x("Bob");
p = &x;
p->print();
student y("Tom", 101);
p = &y;
p->print();
getch();
}
Output (Stick on blank page opposite to code)
Download Output