class Address
{
private:
string city;
string state;
public:
Address(string c, string s) : city(c), state(s) {}
void display()
{
cout << city << ", " << endl;
}
};
class Person
{
private:
string name;
Address* addr = nullptr; // (a)
public:
Person(string n, string c, string s)
: addr(new Address(c, s)), name(n) // (b)
Person(string n) : addr(nullptr), name(n) {} // (c)
void display()
{
cout << name << end;
if (addr != nullptr) // (d)
addr->display(); // (e)
}
void setAddress(string c, string s)
{
if (addr != nullptr) // (f)
delete addr;
addr = new Address(c, s); // (g)
}
};
class Student : public Person // (h)
{
private:
double gpa;
public:
Student(string n, double g, string c, string s)
: Person(n, c, s), gpa(g) {} // (i)
void display()
{
Person::display(); // (j)
cout << gpa << endl;
}
}
|
|
- Building aggregation: The part class name, Address, is a data type, and addr is the object's name. The asterisk makes addr a pointer.
- C++ uses the part object's name to call its constructors. The arguments in the constructor calls match its parameters.
- If the pointer is not initialized in the class specification (a) and not assigned an object in a constructor (b), it must be initialized to
nullptr .
- Calling a function with a null or otherwise invalid pointer is a runtime error. The if-statement prevents this error, increasing the class's security and robustness.
- Using aggregation: The part class name and the arrow operator, adder->, call the Address display function (i.e., sends the "display" message to the addr object).
- The if-statement determines if the Person has an aggregated Address and deallocates it if it does. Failing to deallocate an unneeded aggregated part creates a memory leak. The if-test is probably not required with most modern compilers - only the
delete operation is required.
- Creates a new Address object and aggregates it to the Person.
- Building inheritance: Student is the subclass and Person the superclass.
- Initialize inheritance with a superclass constructor call. Always the first initializer operation, the arguments in the call match the constructor parameters.
- Using inheritance: The superclass name and scope resolution operator call the Person display function.
|