MC logo
PrintMeLots Class
[^] Code Examples
<<PrintMe2 Class printmult.h PrintMeLots2 Class>>
#ifndef _PRINTMULT_H_
#define _PRINTMULT_H_

#include <iostream>

 * This class is constructed with an integer, which it
 * will print repeatedly surrounded by [].
class PrintMeLots: public PrintMe {
        int count;              // Here is the repeat count.
        // Remember the number.
        PrintMeLots(int num, int cnt): PrintMe(num) { 
                count = cnt;

        // Print the string.
        void print() { 
                for(int m = count; m > 0; m--)


Derived classes are created using a colon instead of the word extends as in Java. After the colon is a keyword public, private or protected, which controls how non-public fields are inherited. Always use public. This gives visibility similar to Java: The derived class has access to public and protected members of its base class, and user code has access to inherited public fields.

The colon construct after the constructor is called an initializer list. (In general, it can hold several things.) This is how you call the base class constructor in C++, which does not have super. The initializer list is executed before the body of the constructor, which guarantees that the base class part of the derived class has been constructed before the derived class constructor runs. An initializer list is required if the base class does not have a default (zero-argument) constructor.

Finally, the derived class uses the base class name and the :: operator to call a method of the base class. This is only necessary when the derived class overrides the function.
<<PrintMe2 Class PrintMeLots2 Class>>