26287 total geeks with 3498 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: May 31
May Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
Google slashes App
Engine NoSQL data
storage prices by
25 per cent
Orange customer
clobbered with SIX
FIGURE phone bill
Tipsters exposed
after South
Africa"s national
police force hacked
Samsung flogs slim,
flashy new model:
Protection included
Another Chinese
thing you can see
from space:
Lenovo"s sales
New York cop in
alleged
love-polyhedron
email hack spree
Penguin pays $75m
to settle ebook
price-fixing case
"Leccy car biz
baron Elon Musk:
Thanks for the
$500m, taxpayers...
Apple cored:
Samsung sells 10
million Galaxy S4
in a month
Brit spooks bugged
Edward VIII"s
phones, records
reveal
Slashdot
Sears Is Turning
Shuttered Stores
Into Data Centers
Ethernet Turns 40
Main US Weather
Satellite Fails As
Hurricane Season
Looms
Ask Slashdot: How
To Determine If a
Video Has Been
Faked?
Curiosity Rewarded:
Florida Teen
Heading to Space
Camp, Not Jail
A Cold Look at Cold
Fusion Claims: Why
E-Cat Looks Like a
Hoax
NVIDIA GeForce GTX
780 Offers 2,304
Cores For $650
French Police End
Missing Persons
Searches, Suggest
Using Facebook
Kim Dotcom Wants
Money From Google,
Twitter For
2-Factor
Authentication
Meet Pidora, the
New Official Fedora
Remix For Raspberry
Pi
Article viewer

Inheritance, Polymorphism, Virtual Functions And Jefferson Airplane.



Written by:dimport
Published by:CodeX
Published on:2003-06-21 07:19:46
Topic:C++
Search OSI about C++.More articles by dimport.
 viewed 7686 times send this article printer friendly

Digg this!
    Rate this article :
Inheritance, its a bit of a chuckle, although c++ isnt a 'true' oo language, its inheritance system is pretty damn cool imo, the followiing will show you how to inherit/derive classes, the true nature of c++ polymorphism and will tell you just what the buggery a virtual function is, and how they work. There'll probably no 70's supergroups though.

Inheritance is a way you can build hierarchies or relationships from classes, imagine a 'vehicle' class with several base functions, 'start' and 'stop' then imagine a derived or inherited class called 'car' that will have access to the original 'vehicle' functions of stop and start, but will add specialised functions, for example 'accelerate' 'brake' and 'change gear'. This is a good example of inheritance, derivation and specialisation.
The syntax to derive a class is:

class car : public vehicle

Simple enough, the following example shows a derived 'Car' class, and demonstrates how to use a derived object as well as the relationship between the constructors:

 enum MAKE {Ford, Toyota, Vauxhall, Honda, Volvo};
 class Vehicle
{
public:
    Vehicle() { cout << "Vehicle constructed" << endl; }
    ~Vehicle() { cout << "Vehicle deconstructed" << endl; }
     int GetYear() { cout << itsYear << endl; return itsYear; }
    int SetYear(int year) {return itsYear = year; }
     void Start() { cout << "vehicle started" << endl; }
    void Stop() { cout << "vehicle stopped" << endl; };
 protected:
    int itsYear;
};
 class Car : public Vehicle
{
public:
    Car() { cout << "Car constructed" << endl; }
    ~Car() { cout << "Car deconstructed" << endl; }
     MAKE GetMake() { cout << itsMake << endl; return itsMake; }
    void SetMake(MAKE make) {itsMake = make; }
 protected:
    MAKE itsMake;
};
 int main()
{
    Car myCar;
    myCar.SetYear(1993);
    myCar.SetMake(Toyota);
    myCar.Start();
    myCar.GetYear();
    myCar.GetMake();
    myCar.Stop();
    return 0;
}


Pleasant, an object of the 'Car' class has access to the start/stop functions of the vehicle class, through inheritance. Taking polymorphism to the next step, we can assign a pointer to our base class (Vehicle) and create an object of our derived class with it (Car).

Vehicle* pVehicle = new Car;

This will create a car object on the heap. This is what polymorphism is all about, you can create a shedload of objects but they could all access a virtual function (lets say accelerate) if you were to create a pointer and assign all the objects to that pointer, you could call the virtual accelerate function without any regard for scope etc, to demonstrate;

 class Vehicle
{
public:
    Vehicle():itsYear(1984) { cout << "Vehicle constructed" << endl; }
    ~Vehicle() { cout << "Vehicle deconstructed" << endl; }
    void Start() { cout << "Vehicle starts" << endl; }
    void Stop() { cout << "Vehicle stops" << endl; }
    virtual void Accelerate() { cout << "Vehicle accelerates" << endl; }
protected:
    int itsYear;
};
 class Car : public Vehicle
{
public:
    Car() { cout << "Car constructed" << endl; }
    ~Car() { cout
<< "Car deconstructed" << endl; }
    void Accelerate() { cout << "Car Accelerates" << endl; }
};
 int main()
{
    Vehicle *pCar = new Car;
    pCar->Start();
    pCar->Accelerate();
    pCar->Stop();
    return 0;
}


By declaring Vehicle's Accelerate function as virtual basically indicates that at some point this class will be derived from and that this function will get overridden, in main() we create a pointer to a vehicle but assign it the address of a car, because a car is a vehicle, thats fine with the compiler, then the pointer is used to call the accelerate function, because accelerate is virtual, the overriding function in the car class is invoked, pleasant, note this only works via pointers and references, passing it by value wont work.

As I've been demonstrating by adding output statements to the constructors, to construct an object in a derived class involves first calling the base constructor, then the derived constructor. When a virtual function is invoked in an object, it must keep track of the function, to do this a compiler will build whats known as a virtual function table, one is created for each type, each object of that type keeps whats known as a vptr (virtual table pointer) which points to that table.

This article was originally written by Pigsbig78

Did you like this article? There are hundreds more.

Comments:
Quantris
2006-07-26 17:34:10
I'll probably be writing a similar article to this in the near future, but looking at multiple dispatch (which I somehow managed to figure out after a few days).
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
harry
Blog entry for Thu 28th Sep 12pm on Thu 28th Sep 12pm
Hi In school i want to net send my mates but hide who its coming off any ideas. no programs though as the machine in school sets off an alarm if it detects any batch files etc... thanks Harry


     
Your Ad Here
 
Copyright Open Source Institute, 2006