Constructors and inheritance

When a class inherits from another class, often the subclass will want to have its own constructors that refer back to the parent class’s constructors.

Bank account example

Consider the following class hierarchy:

The BankAccount class should have a constructor that allows the owner and balance properties to be set:

Now, the MoneyMarketAccount class should use those constructors in its own constructors, like so:

In order to call the parent’s constructor, we use the : followed by the parent’s constructor function call (e.g. BankAccount(_owner)).

Public, protected, private

The BankAccount class above has two private data members (indicated by the minus signs in the diagram): owner and balance. Why should those be private? We don’t want to allow other classes or other code to decide that the owner has changed, or that the balance has changed without using the deposit or withdraw function.

Here is how we specify that those variables are private:

The construct for BankAccount (as shown above) sets the values for owner and balance, and the deposit and withdraw functions change the balance. However, given a BankAccount object myaccount, how do we find out the owner and the balance? These are private data members, so we are not allowed to do this: cout << myaccount.balance << endl;

Now we can find out the balance like this: cout << myaccount.getBalance() << endl; Notice there is no function for changing the balance (except via deposit and withdraw, which are not shown here).

A class may also have private methods. For example, maybe both the deposit and withdraw methods call a method named notifyOwnerByEmail that send deposit/withdraw receipts to the owner. This method should only be used after a deposit or withdraw, so there is no reason for other code to call notifyOwnerByEmail directly. Thus, that method should be private, so that only code that is part of the BankAccount class can use the method.

You can also put constructors in the private section. If all constructors are marked as private, then no instances of the object can be created. This is a rarely-used but sometimes necessary feature.

Here is how public/protected/private works in terms of inheritance (copied from StackOverflow):

Post scriptum

class n. & adj. [Origin: Latin classis via calare, “to call to arms.”] 1 n. (Object-orienteering) Data members encapsulated with a set of methods dying to get at them. 2 n. (Marxism) A subset of society encapsulated with a set of methods for exploiting and exterminating both itself and other subsets of society. 3 n. (Style) Someth’n’ you jest plain got or don’t. 4 adj. (Of a struggle) iterative, as in the attempted modularization of real-world activities. – The computer contradictionary