Strath
Strath

Reputation: 41

Print Inheritance Function

I am attempting to complete a past Object Oriented Programming examination paper that involves inheritance in C++. This is the UML This is the UML.

I am trying to print the second line of the sample output, as shown on the question paper. The program should use inheritance to output the student name, DOB, and the department, but I am not sure how to output the first two. I have implemented inheritance but the print functions of the Person and Date classes do not print. Full code implementation here.

This is the Student class:

#include "Person.h"

class Student :
    public Person
{
public:
    Student(string, string, int, int, int);
    void print();
    ~Student();
private:
    string Dept;
};

Student::Student(string d, string name, int mm, int dd, int yy)
    : Person(name, mm, dd, yy)
{
    Dept = d;
}

void Student::print()
{
    cout << Dept;
}

This is the Person class:

#include "Date.h"

class Person
{
public:
    Person(string, int, int, int);
    void getName();
    void setName(string);
    void print();
    ~Person();
private:
    string Name;
    Date DOB;
};

Person::Person(string n, int bmonth, int bday, int byear)
    : DOB(bmonth, bday, byear)
{
    setName(n);
}

void Person::getName()
{
    cout << Name;
}

void Person::setName(string nm)
{
    Name = nm;

}

void Person::print()
{
    getName();
    cout << ", DOB: ";
    DOB.print();
}

Test output:

Student s("Applied Computing", "James Hall", 12, 12, 1988);
    cout << endl;
    cout << "Student created: ";
    s.print();

Upvotes: 2

Views: 1580

Answers (1)

Ricardo Costeira
Ricardo Costeira

Reputation: 3331

Are you trying to run the exact code that you supplied? Because it's missing the main function.

s.print() will never call the Person class print method, since you define a method with the same name in Student. Hence, it will only print the student's name. If you want to use the base class method, you have to either call it explicitly in the derived class' method (for instance, by writing Person::print() in the Student class print method), or simple not define another method with the same name on the derived class (you should read up on how inheritance and virtual classes works in C++). For your problem in particular, you'll want the first option, i.e., something like:

void Student::print()
{
  Person::print();
  cout << ", " << Dept << endl;
}

Also, it's good practice to flush the stream. Output streams are buffered, so you either flush them manually or hope that they get flushed. Add a cout << endl or a cout << flush at the end of printing.

Upvotes: 2

Related Questions