Code About Us Tutorial


  Inheritance
    What is Inheritance?
    Creating a Derived Class
    Creating an Object
    Simple Inheritance
    Overloading Derived Classes
    Dominating Member Functions
    Polymorphism & Virtual Functions


   
 

Home > Inheritance > Overloading Derived Classes

November 29, 2009 3:50 pm

   

Overloading Derived Classes

Overloading a derived class is the same as overloading any kind of class. Here is a skeleton example of Overloading a derived class.

 

 
//superset(derived class)

class Employee: public Business { public: Employee(); //constructor

Employee(int age); //overloaded

Employee(int age, long int Sal); //overloaded

Employee(int age, long int Sal, int years); //overloaded

~Employee(){};

void setAge(int age) {itsAge = age;} int getAge() const {return itsAge;} void Comment() const {cout <<"I sure do love programming!n";} void WakeUp() const {cout <<"Wow! I sure didn't get enough sleep!n";} void Sleep() const {cout <<"Goodnight!n";} protected: int itsAge; };

In this example, the derived class is named Employee and the base class is named Business. As you can see, overloading the constructor of a superset is the exact same as overloading the constructor of a regular class. You can also override the methods of the base class. For instance, if you had a base class named Human, and two derived classes named Male and Female. If you wrote:

 

 
//tq.h

//overriding

//base class

class Human { public: Human() { itsAge = 16;} ~Human(){};

int getAge() const { return itsAge;} void setAge(int x) { itsAge = x;}

void Speak() const {cout << "I'm a human, hello world!n";} protected: int itsAge; };

//derived class

class Male: public Human { public: Male(){}; ~Male(){};

void Speak() const { cout <<"I'm a male, hello world!n";} };

//derived class

class Female: public Human { public:

Female(){}; ~Female(){};

void Speak() const { cout <<"I'm a female, hello world!n";} };

Here is the main .cpp:

 

 
#include <iostream.h>
#include "tq.h"

int main() { Human Human1; Human1.Speak(); Male Male1; Male1.Speak();

Female Female1; Female1.Speak();

return 0; }

If you compiled this program, you would notice that each object returns their own message, even though each Class has the same name and return type. Please Rate this Code:


    Comments for: Overloading Derived Classes
  There are NO user contributed comments for Overloading Derived Classes.



Add Comment:
Name:
Email:


 «1» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.