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 > Creating an Object

November 29, 2009 7:53 am

   

Creating an Object

Now if you wanted to create an object from the derived class, you could use the following code:

 

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

int main() { cout <<"Here is an example of inheritance...." << endl;

cout<<"Using Base class, Creating a Reptile...." << endl; Reptile Dinosaur;

cout<<"Lets See how much the first Dinosaur Weighed and the Size..nn"; cout <<"Name: Dinosaurn"; cout <<"Size: " << Dinosaur.getHeight() << endl; cout <<"Weight: " << Dinosaur.getWeight() << endl; cout <<"nn"; cout <<"Using Derived class, Creating a Lizard...." << endl; Lizard KamotoDragon;

cout <<"Lets find out the size, weight, and age of this lizard...nn"; cout <<"Name: Kamoto Dragonn"; cout <<"Size: " << KamotoDragon.getHeight() << endl; cout <<"Weight: " << KamotoDragon.getWeight() << endl; cout <<"Age: " << KamotoDragon.getAge() << endl;

return 0; }

As can be seen, I create an object the same way as you would with any other class. Notice I did not set its Height or Weight, nor did I need to because the base class (Reptile) had a constructor that set the Height and Weight when the object was created. When you create a derived class, the base class constructor is called first followed by the derived class constructor. The derived class has all the member functions and data that the base class had. You can add more to the base class by making a derived class. In this example I added a new member variable, itsAge, and I added two new functions, Regenerate and Run from Predator. If you want to access the new functions I added just type the following:

 

 
Lizard KamotoDragon;

KamotoDragon.

KamotoDragon.RegenerateTale(); KamotoDragon.RunFromPredator();

And you would get the console output:

Regenerating… Running….

The base class does not get the new functions you added to the derived class. If you written

 

 
Reptile Dinosaur;

Dinosaur.RegenerateTale(); //you would get an error.

Please Rate this Code:


    Comments for: Creating an Object
  There are NO user contributed comments for Creating an Object.



Add Comment:
Name:
Email:


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