<< Chapter < Page Chapter >> Page >

#include<string.h>

class Person

{

private:

int idnum;

char lastName[20];

char firstName[15];

public:

void setFields(int, char[], char[]);

void outputData( );

};

void Person::setFields(int num, char last[], char first[])

{

idnum = num;

strcpy(lastName, last);

strcpy(firstName, first);

}

void Person::outputData( )

{

cout<<“ID#”<<idnum<<“ Name: “<<firstName<<“ “<<lastName<<endl;

}

// derived class

class Employee:public Person

{

private:

int dept;

double hourlyRate;

public:

void setFields(int, char[], char[], int, double);

};

void Employee::setFields(int num, char last[], char first[], int dept, double sal)

{

Person::setFields(num, last, first);

dept = dep;

hourlyRate = sal;

}

int main()

{

Person aPerson;

aPerson.setFields(123, “Kroening”, “Ginny”);

aPerson.outputData();

cout<<endl<<endl;

Employee worker;

worker.Person::setFields(777,”John”, “Smith”);

worket.outputData();

worker.setFields(987,”Lewis”, “Kathy”, 6, 23.55);

worker.outputData();

return 0;

}

The output of the above program:

ID # 123 Name: Ginny Kroening

ID # 777 Name: John Smith

ID # 987 Name: Kathy Lewis

In the above program, when you use the Employee class to instantiate an Employee object with a statement such as Employee worker; and then the statement worker.setFields(); uses the child function with the name setFields(). When used with a child class object, the child class function overrides the parent class version. On the other hand, the statement worker.outputData(); uses the parent class function because no child class function has the name outputData().

Overriding a base class member functions with a derived member function demonstrates the concept of polymorphism. Recall that polymorphism permits the same function name to take many forms.

Constructors and destructors in derived classes

When you derive one class from another class, you can think of any instantiated object of the derived class as having two portions:

  • the base class portion and
  • the derived class portion.

During the instantiating process, the base class portion of the object is instantiated, and then the derived class portion of the object is instantiated.

So, two constructors execute for a single derived class object: the base class constructor and the derived class constructor.

When a derived class object instantiates, constructors begin executing at the top of the class hierarchy. First, the base constructor executes, then any indirect base class’s constructors execute. Finally, the derived class’ constructor executes.

When an object is destroyed, class destructors are executed in the reverse order. First, the derived class’s destructor is called, then the destructors for any indirect base classes, and finally, the destructor for the base class. Figure below illustrates this process using a class hierarchy with four levels.

The order of construction makes sense, since it allows base classes to perform any initialization on class members that may be used by derived classes. And the order of destruction ensures that any base class members required by derived classes are not destroyed until all objects of any derived classes are destroyed first.

Execution of constructors and destructors in a class hierarchy.

Example

#include<iostream.h>

#include<string.h>

class Person

{

private:

int idnum;

char lastName[20];

char firstName[15];

public:

Person();

void setFields(int, char[], char[]);

void outputData( );

};

Person::Person(){

cout<<“Base class constructor call “<<endl;

}

void Person::setFields(int num, char last[], char first[])

{

idnum = num;

strcpy(lastName, last);

strcpy(firstName, first);

}

void Person::outputData( )

{

cout<<“ID#”<<idnum<<“ Name: “<<firstName<<“ “<<lastName<<endl;

}

class Customer:public Person

{

private:

double balanceDue;

public:

Customer();

void setBalDue;

void outputBalDue( );

};

Customer::Customer(){

cout<<“Derived constructor called”<<endl;

}

void Customer::setBalDue(double bal)

{

balanceDue = bal;

}

void Customer::outputBalDue()

{

cout<<“Balance due $”<<balanceDue<<endl;

}

int main()

{

Customer cust;

cust.setFields(215, “Santini”, “Linda”);

cust.outputData();

cust.setBalDue(147.95);

cust.outputBalDue();

return 0;

}

The output of the above program is:

Base class constructor called

Derived class constructor called

ID #215 Name: Linda Santini

Balance due $147.95

The output shows that both the constructor of Person class and the constructor of Customer class involve in creating the object Cust.

Questions & Answers

what is mutation
Janga Reply
what is a cell
Sifune Reply
how is urine form
Sifune
what is antagonism?
mahase Reply
classification of plants, gymnosperm features.
Linsy Reply
what is the features of gymnosperm
Linsy
how many types of solid did we have
Samuel Reply
what is an ionic bond
Samuel
What is Atoms
Daprince Reply
what is fallopian tube
Merolyn
what is bladder
Merolyn
what's bulbourethral gland
Eduek Reply
urine is formed in the nephron of the renal medulla in the kidney. It starts from filtration, then selective reabsorption and finally secretion
onuoha Reply
State the evolution relation and relevance between endoplasmic reticulum and cytoskeleton as it relates to cell.
Jeremiah
what is heart
Konadu Reply
how is urine formed in human
Konadu
how is urine formed in human
Rahma
what is the diference between a cavity and a canal
Pelagie Reply
what is the causative agent of malaria
Diamond
malaria is caused by an insect called mosquito.
Naomi
Malaria is cause by female anopheles mosquito
Isaac
Malaria is caused by plasmodium Female anopheles mosquitoe is d carrier
Olalekan
a canal is more needed in a root but a cavity is a bad effect
Commander
what are pathogens
Don Reply
In biology, a pathogen (Greek: πάθος pathos "suffering", "passion" and -γενής -genēs "producer of") in the oldest and broadest sense, is anything that can produce disease. A pathogen may also be referred to as an infectious agent, or simply a germ. The term pathogen came into use in the 1880s.[1][2
Zainab
A virus
Commander
Definition of respiration
Muhsin Reply
respiration is the process in which we breath in oxygen and breath out carbon dioxide
Achor
how are lungs work
Commander
where does digestion begins
Achiri Reply
in the mouth
EZEKIEL
what are the functions of follicle stimulating harmones?
Rashima Reply
stimulates the follicle to release the mature ovum into the oviduct
Davonte
what are the functions of Endocrine and pituitary gland
Chinaza
endocrine secrete hormone and regulate body process
Achor
while pituitary gland is an example of endocrine system and it's found in the Brain
Achor
what's biology?
Egbodo Reply
Biology is the study of living organisms, divided into many specialized field that cover their morphology, physiology,anatomy, behaviour,origin and distribution.
Lisah
biology is the study of life.
Alfreda
Biology is the study of how living organisms live and survive in a specific environment
Sifune
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Programming fundamentals in c++. OpenStax CNX. Jul 29, 2009 Download for free at http://cnx.org/content/col10788/1.1
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Programming fundamentals in c++' conversation and receive update notifications?

Ask