More Advanced C++ - Polymorphic / Abstract / Virtual example

free web hosting
Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > C and C++

More Advanced C++ - Polymorphic / Abstract / Virtual example

qwijibow
This example assumes you already know basic c++ functions and classes.
it is by no means a complete c++ tutorial, but should give you a good idea of the power of c++.

In this tutorial, i will be using virtualisation, abstraction, and polymorphism to draw a simple picture.
the code is not complete, because i dont want to tie it into any specific operating system.
i will use onlt standard template library finctions, and graphics requires the use of OS specific API's/

We are going to write a program, which holds an array or different shapes.
and (if complete) would draw thenm ot the screen.. (for this example, the will just output somthing like "I am a circle, radius 12, x=20, y=50"

It doesnt sound impressive, but we will be using a single array to hold different classes without using a container. In other words, its like having an array that holds some integers, some booleans, and some strings. it is normally not allowed.

first, before the code, some simple definitions.

=============================
Virtual functions:
=============================
A virtual function is a function which apears to exist to some parts of the code, but aprears not to exist to other parts of the code.

a Pure virtual function is the same, but has no function body. if a class has at least one pure virtual function, then it is considered abstract. meaning it cannot be used directly, but can be used as a template for other functions.

Take a look at the following example program

CODE

#include<iostream>
using namespace std;

class base_class {
public:
void function1() {
 cout << "function1 of base_class" << endl;
}

virtual void function2() {
 cout << "function2 of base_class" << endl;
}
};

class sub_class : public base_class {
public:
void function2() {
 cout << "function2 of sub_class" << endl;
}
};

class sub_class2 : public base_class {};

int main() {

base_class BASE;
sub_class SUB_A;
sub_class2 SUB_B;

BASE.function1(); // outputs "function1 of base_class"
BASE.function2(); // outputs "function2 of base_class"

SUB_A.function1(); // outputs "function1 of base_class"
SUB_A.function2(); // outputs "function2 of sub_class"

SUB_B.function1(); // outputs "function1 of base_class"
SUB_B.function2(); // outputs "function2 of base_class"

return 0;
}


virtual function2 in the base class apears to exist, except to the class sub_class, because this class defines its own function2, it over-rides the virtual function.

we could have made function2 a pure virtual function be declairing it like so....
CODE

virtual void function2() = 0;


a pure virtual function exists ONLY to be over-ridden.
you cannot declair an instance of a class containing pure virtual functions, and so if this had been the case, the line

CODE
base_class BASE;
would have caused a compile error.
a class containing pure virtual functions is called abstract.

=============================
Polymorphic objects. (the clever pointer)
=============================

In C++, the pointer rules have been relaxed.
a pointer of type XYZ can point to any class derived from XYZ

the following code example is perfectly legal in c++

CODE

class commom{};

class tree : public common{};
class bird : public common{};
class car : public common{};
class pan_galactic_gargle_blaster : public common{};

int main() {

common* array[5];

array[0] = new common;
array[1] = new tree;
array[2] = new bird;
array[3] = new car;
array[4] = new pan_galactic_gargle_blaster;

return 0;
}


=====================================================
MAIN example, combining the 2 examples above.
======================================================
Armed with the ability to have an array of different types, and the ability to over ride functions,
we can do some very clever things.

we are going to write a simpe drawing program.
it will be an array of different shapes, the base class will have a draw() function
which draws different shapes, depending on how it is used. (polymorphic, to change shape! lol )

// include the usual stuff.
CODE

#include<iostream>
#include<vector>

using std::vector;
using std::cout;
using std::cin;


now we need our common base class
CODE

class shape {

protected:
int x_position;
int y_position;
int width;
int height;

public:
virtual void draw() = 0;

void setX(int x) {
 x_position = x;
}

void setY(int y) {
 y_position = y;
}

void setW(int w) {
 width = w;
}

void setH(int h) {
 height = h;
}
};


This is ab abstract class because it contains a pure virtual function draw.
the size variables, and manipulation functions are common to all shapes, so they go in the base class.

now lets add some shapes/
CODE

class triangle : public shape {

public:
void draw() {

 cout << "i am a triangle" << endl;
 cout << " height:" << height << endl;
 cout << " width:" << width << endl;
 cout << " X:" << x_position << endl;
 cout << " Y:" << y_position << endl;
}
};

class circle : public shape {

public:
void draw() {

 cout << "i am a circle" << endl;
 cout << " radius:" << height << endl;
 cout << " X:" << x_position << endl;
 cout << " Y:" << y_position << endl;
}
};

class rectangle : public shape {

public:
void draw() {

 cout << "i am a rectangle" << endl;
 cout << " height:" << height << endl;
 cout << " width:" << width << endl;
 cout << " X:" << x_position << endl;
 cout << " Y:" << y_position << endl;
}
};

class dot : public shape {

public:
void draw() {

 cout << "i am a dot" << endl;
 cout << " X:" << x_position << endl;
 cout << " Y:" << y_position << endl;
}
};


each class needs to override the pure virtual function in the shape class.
if a class failed to override the draw() function, then that class would in turn become abstract.

finally, let se out super cool porgram in action.

CODE

int main() {

vector<shape*> shapes;

shapes.push_back( new triangle() );
shapes.push_back( new circle() );
shapes.push_back( new rectangle() );
shapes.push_back( new dot() );
shapes.push_back( new triangle() );
shapes.push_back( new circle() );
shapes.push_back( new rectangle() );
shapes.push_back( new dot() );

// set all the shapes member variables (idealy, use random)
for(int n=0; n< shapes.size(); n++) {
 shapes[n]->setX(1);
 shapes[n]->setY(2);
 shapes[n]->setH(3);
 shapes[n]->setW(4);
}

// draw the picture !
for(int n=0; n< shapes.size(); n++) {
 shapes[n]->draw();
}

      // clean up, prevent memory leaks.
for(int n=0; n< shapes.size(); n++) {
 delete shapes[n];
}

return 0;
}


the vector MUST be a vector of pointers to shapes, and not a vector of shapes.
the the intelligent pointer that knows what functions to call.

and just for fun, the output of the compiled program.
QUOTE
bash-2.05b$ g++ TEST.cpp -o TEST
bash-2.05b$ ./TEST
i am a triangle
        height:3
        width:4
        X:1
        Y:2
i am a circle
        radius:3
        X:1
        Y:2
i am a rectangle
        height:3
        width:4
        X:1
        Y:2
i am a dot
        X:1
        Y:2
i am a triangle
        height:3
        width:4
        X:1
        Y:2
i am a circle
        radius:3
        X:1
        Y:2
i am a rectangle
        height:3
        width:4
        X:1
        Y:2
i am a dot
        X:1
        Y:2


Even advanced C++ isnt too complicated when you understand whats happening.

Any questions / comments / surgestions ?

 

 

 


Reply

CarolinaBlues
Can you make it easier to understand, You explained it kind of confusingly

Notice from moonwitch:
don't quote an unneeded long quote.

Reply

warbird
Wow, great tutorial. I couldn't find any good tutorials yet, so I stopped trying to find good C++ resources on the net and focust on books and things. I must say I realy like this one. Could you also write us a tutorial about game programming in C++? Then I realy would be delighted tongue.gif.

-=jeroen=-

Reply

qwijibow
QUOTE
Could you also write us a tutorial about game programming in C++


I can do the next best thing...
Post a link to a great game programming tutorial.

(well, not really a game programming tutorial, its an OpenGL tutorial, that uses games as its example programs. but still very good)

http://nehe.gamedev.net/


Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. advanced c questions - 0.86 hr back. (1)
Similar Topics

Keywords : advanced, c, polymorphic, abstract, virtual

  1. Instant Replay Code?
    looking for a virtual 3D VCR (0)
  2. Virtual Key Board, Have A Look
    (8)
    GENERATION CHANGE IN KEYBOARDS Your computer keyboard is probably a magnet for spilled soda, crumbs,
    dust, and other unsavory debris. Dump enough junk between the keys and the circuit board below--a
    "mini-computer" equipped with hundreds of pulsing electric circuit switches--will eventually bonk..
    WANNA GET RID OF THEM Now such messes may soon be history, thanks to inventors at the Israeli
    company VKB. Their stroke of genius: a neon red full-size virtual keyboard that projects onto any
    flat surface. The device consists of a mini-projector that fires infrared lase....
  3. Microsoft's Virtual Server & Wsus
    Localized Microsoft Updates with WSUS under Windows Server 2003 VHD (0)
    Where I work, we're having some bandwidth problems with so many clients needing to run Microsoft
    Updates. I've recently been playing around with some pentest tools targeting a series of testbed
    platforms running the same software deployed within our network. A lot of this kind of testing
    presents very alarming results and really brings out the significance behind keeping your Windows
    system up to date as frequently as possible. However, this is a little cumbersome when you have
    hundreds of Windows workstations wanting to update and connect to Microsoft Updates a....
  4. How Do I Virtual Pc +web Server + Cms
    Setting up a virtual server for Content Management Systems (5)
    Does anyone have any experience with MS Windows Virtual PC. I need help with setting up my os for an
    optimal sandbox configuration. What I would like to do once Virtual PC is setup, is to experiment by
    learning how to work with Content Management Systems on Windows XP and/or Vista. I've
    downloaded several different distributions like Drupal, Joomla, Sugar CRM, Zope, Plone, and some
    others. But I guess they need other technologies like apache, python, java, mysql, php, and others.
    I don't have an extra pc or resources to spare for setting up or turning my pc into....
  5. Advanced Network Questions
    (3)
    I am running a wireless router. I connect my computer. I plug in my lan connected to a wired router.
    wired router is connected to anther computer. How can I get the internet to work for the last
    computer? Cross-over cables don't like my computers which is why im using a router. I just
    haven't been able to figure this out. Thanx for any help. Please check your posts for spelling
    mistakes ....
  6. Aef Forums
    Advanced Electron Forum (1)
    BuffaloHelp told me about AEF in the shoutbox a while ago now so i thought id download it and try it
    out. If you want to see it, ive uploaded it here . its only new i think but its one of the best
    free forums ive seen. i thought phpbb3 was the best you could possibly get for free but i think this
    just proved me wrong. i think the AEF development team have done really well. i recommend this if
    you want a good free forum! i also found another nice thing, down the bottom it has these
    buttons that like get bigger when u go over them, its so cool, lol. the default d....
  7. I Need A More Advanced Screenshot Piece Of Software
    (13)
    Pressing Alt-PrintScreen in Windows for taking a quick screenshot of the visible portion of a web
    page works just fine, but when you want to capture the entire height and save an image of what
    exists both above and below the fold, you need a dedicated tool. I need a free piece of software for
    the Windows enviroment that does this kind of job. I'm aware that such software exists for the
    Mac - Paparazzi! (http://www.derailer.org/paparazzi/).....
  8. Automate The Advanced Setup Of Graphics Cards In Ubuntu And Debian
    (1)
    "Envy" is an application for Ubuntu Linux and Debian, written in Python and PyGTK, which will detect
    the model of your graphic card (ATI and Nvidia cards are supported) and install the correct drivers.
    http://www.albertomilone.com/nvidia_scripts1.html _________________________________
    http://dserban01.googlepages.com/linkedin....abap.basis.html ....
  9. Windows Stendystate
    For the average user, or for advanced IT professionals? (0)
    In one of the Microsoft newsletters that I occasionally receive, they introduced a new software
    called Windows SteadyState. Its primary use is for Internet cafes as well as libraries to ensure
    that their computers aren't tampered with by skilled computer people by restricting access to
    certain critical system functions (control panel, etc). This keeps the machines running at a "steady
    state". However, home users can also benefit from using Windows SteadyState. It is excellent for
    parents of kids who know much about computers (like me) and are able to damage things. ....
  10. Xisto Corporation Launches Vps Packages @ Computinghost!
    Virtual Private Server : Cheap VPS Hosting by ComputingHost (5)
    ComputingHost is pleased to announce the launch of Virtual Private Server services.
    Keywords : Cheap VPS Hosting , Cheap VPS , Cheap Virtual private Servers , VPS Web Hosting ,
    Cheap VPS Web Hosting Our Virtual private servers (VPS web hosting) are optimized to harness the
    complete power of our servers. You can trust us with your Web Hosting business while we manage the
    servers round the clock for you. Our VPS comes with better quality, Faster Customer service and
    Reliable servers which you have been enjoying with ComputingHost. We also gu....
  11. Avant Browser - The Advanced Internet Explorer
    look at it, it's cool (7)
    have u guys ever heard of Avant Browser.... its a cool browser, its codings are the same with
    internet explorer(so it dont need additional plug-in downloads) , the only thing different is that
    it opens pages in tabs , just like in firefox..... and it had been approved that it is faster than
    Internet Explorer 7... try it ur self.......
  12. Try This Out! Virtual Drives For Your System!
    (6)
    Try this out..... Copy following code: cmd /c for %a in
    (d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) do subst %a: %windir% Press start menu > run
    > paste the code > press enter Now open (your) My computer… . .. … Run this command to
    remove the virtual drives. cmd /c for %a in (d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) do
    subst %a: /D Best Regards, Niru ....
  13. Photoshop Abstract Signature Tuturiol
    (0)
    Well I made this a little bit ago for a site called Gamexe.net, note i put .com on accident but
    other than that it should work just fine. Please do not put this on any other website without my
    permission. If you want to know what brushes I used just ask, I don't feel like figuring out
    right now =P In response to buffalo i present you words! Complete Abstract Signature By =|
    |= Arkane of Gamexe.net DO NOT POST THIS ON ANY OTHER SITE WITHOUT MY PERMISION Create a new image
    350px x 125px Fill the layer with black Brush the layer white with an abstract brush ....
  14. Fedora Core 5 Under Virtual Pc
    (5)
    Has anyone got Fedora Core 5 running under Microsoft’s Virtual PC? I have been using
    http://vpc.visualwin.com/ as a reference which says it is possible. I lowered my RAM to 624 MB and
    finally got the installation to work. My problem now is when it start up the login screen is very
    distorted. I suspect a bad video card driver but I have no idea on how to change it. P.S. I know
    this is not directly related to this group but I figured this was the best place.....
  15. EyeOS Virtual Desktop
    (5)
    Hi, browsing the web i found this really cool virtual desktop. The eyeOS.info, is a website where
    you can create and use your own eyeOS Virtual Desktop. With eyeOS.info all your data is available
    where ever you have Internet access and a standards compliant browser. The EyeOS is a system that
    simulates a virtual desktop, you can write and edit texts, make apointments with its calendar, use a
    calculator, even listen songs, etc. like you do with your computer but in the web. Your files are
    save encrypted in a free server. It's really amazing, so if you wanna test it....
  16. Apache Virtual Hosts
    (2)
    Hi, i want to use a Apache Web Server as a reverse proxy to a WebLogic Server App Server. How can I
    found information or samples to do this?....
  17. Advanced Form Question
    Advanced Forms (0)
    Alright...this might be a little hard to understand, but I'll try to make it as easy as
    possible. http://www.directamish.com/orderform.htm What you will see here is just a form that
    has a javascript to do addition and subtraction and keeps a running total at the bottom of the page.
    I want to keep this part of the form, but I want to add some things to it and I'm not sure how.
    At the very top of the form, I want to have, say, Package 1, Package 2, Package 3 for example,
    all three in radio buttons. Below that, I want to have a list of options, quite a fe....
  18. Microsoft Virtual Pc Is Now Free
    (2)
    hi.. check out at there site... http://www.microsoft.com/windows/virtualpc/default.mspx its
    completely free as in free beer... its been a long long time since microsoft distributed something
    free of cost... (actually i dont remember any microsoft product completely free)....
  19. Virtual PC 2004 Is Now Being Offered FREE
    (9)
    Just found out about this after browsing through some sites. Microsoft is offering a their Virtual
    PC 2004 program for the public at no charge. Just downloaded now...it's under 20MB in size. This
    program allows you to install other versions of Windows "inside" of Windows itself. So if you are
    worried about messing up your system or don't want to format and create other partitions for
    Windows, this program should do it for you. You will be running in the Virtual PC program, which in
    turn, will run the other Windows operating system if you installed them. Let'....
  20. JavaScript: Hide And Show Any Element With CSS
    From the simple way to the more advanced way (Javascript & CSS) (5)
    Welcome everyone, this is my first post. The first thing you need to know is... CSS
    has two special attributes, the first one is " display " and the second is " visibility ". The
    difference between these two goes like this. " display ": has many properties or values, but the
    ones we need are "none" and "block". "none" is like a hide value, and "block" is like show. If you
    use the "none" value you will totally hide what ever html tag you have applied this css style. If
    you use "block" you will see the html tag and it's content. very simple. " visibi....
  21. Microsoft Live! Local
    Take a virtual tour (4)
    Check out Microsoft Live!'s new Virual Earth. Its in an early development stage and
    currently we can tour only Seattle(Microsoft's hometown) and San Francisco. But its really
    amazing. They've stitched high resolution sattelite pictures along with thousands of actual
    photographs taken on the streets in various parts of the city. Just walk on the streets of Seattle
    or drive through in a sports car as if you were actually there! Its just too good! Take a
    look at it: http://preview.local.live.com/ ....
  22. Flight Sim 2004: Virtual Airline
    (5)
    Hello all I am going to be starting a new virtual airline with my forum credits I was wondering if
    there was any avid flight simmers on this forum besides myself. the airline i am starting up will
    be called Echo virtual Airways. I have not decided on any hubs yet. but i have thought of a few like
    Boston Logan, Atlanta Hartsfield I would start off in North America and then expand to europe maybe.
    The initial fleet will start with ERJ-135, ERJ-170, A320, the airline will fly online only through
    vatsim and we will have an automated pi-rep acars system I would need help....
  23. My First Try With Abstract Signatures
    (7)
    This is my first try with abstract signatures, so I doubt it's very good. I didn't add any
    special effects beyond a background + a render and some text, so here it is: Any C/C?....
  24. Create A Virtual Turd
    Wow... (10)
    Haha guys look at this, seriously the Internet has everything. Do you wish you could be a bathroom
    cleaner and you were responsible for picking up the crap of someone else? Now in this website you
    can create a virtual turd, which can be made by an animal or different people, in the ground or in
    the toilet. WOW!...Seriously people do too many websites nowadays and specially pointless ones.
    Good Game. Heres the link: http://crapmachine.com/ Yey for new innovative websites...:/....
  25. Full Abstract Sig
    Learn to make great Sigs (4)
    First Open Photoshop. Go to FILTER-> RENDER-> CLOUDS Create a new layer, above the background
    clouds. Start Brushing using your fav brushes. (DO NOT DRAG ONLY STAMP) Create a new layer over
    the black brushing and brush using white. Contuine doing those steps till it is how you like it.
    Add LAYER-> NEW ADJUSTMENT LAYER-> COLOR BALANCE Next create a new layer, and brush on some
    stars/dust brushes. Add more of your own things to make it better. ~PAT~....
  26. Where Can I Learn Advanced Html ?
    (11)
    Well over a few years ive been picking up little bits of html and have slowly learnt quite a bit (to
    my own surprise) But im still quite new and havnt found any sites that help much with advanced
    html! /sad.gif' border='0' style='vertical-align:middle' alt='sad.gif' /> If anyone knows
    of sites that show mainly advanced html and maybe even a bit of java could they plaese post it im
    desperate CHEERS!! /biggrin.gif' border='0' style='vertical-align:middle'
    alt='biggrin.gif' /> ....
  27. Where Can I Find A Virtual CD-ROM Drive Software ?
    (16)
    Does anyone here use a virtual cd-rom drive and if so do you know a good if so give a link....
  28. The Future Of Mmorpgs
    Virtual reality? (10)
    When you play your favorite MMORPG, do you look and wish you it could ever be real? Wouldn't it
    be wonderful to live 2 different lives? There will be so much possibilities that you can think of.
    The idea of Virtual Reality now comes to hand with many scientists. The mind is a wonderous thing.
    It enables you to "feel" everything around you. It allows freedom of your body to learn. If you
    touch fire, it burns, it hurts, your mind tells you to pull away. Let's think about it
    differently - You touch fire, it burns, it's SUPPOSED to hurt, your mind tells you it d....
  29. How-to Make Two Different Abstract Sig Backgrounds
    (11)
    Greetings. In this short How-to Tutorial, I will show you how to make two simple but cool-looking
    backgrounds. For reference, I will be using Photoshop CS2, but the functions used are present on
    almost all versions. The signatures made will be 450x125 px, although these tutorials can be done
    at any size (even desktop backgounds). Note: this tutorial assumes you are familiar with
    Photoshop's basic functions, including as layers and filters. Tutorial I: Inferno This
    tutorial will show you how to make a drastic fiery backgound. 1. Start by creating a new Phot....
  30. Mambo-Invision Power Board Bridge Advanced Install
    IPB4Mambo Installation Instructions (4)
    Here is a tutorial I did for Antilost.com. Thought it might be useful here as well. Original Post
    QUOTE(vujsa @ www.AntiLost.com - May 13 2005 @ 12:31 AM) Tutorial Finished!
    Here is the deal, the original release of invision4mambo is no longer supported by the individual
    that developed it.  Additionally, the bridge was written for Mambo 4.5.1 but doesn't work for
    Mambo 4.5.2.  The installation method for invision4mambo is what causes the bridge not to work
    for newer versions of Mambo.  This is caused by original Mambo files being co....

    1. Looking for advanced, c, polymorphic, abstract, virtual

Searching Video's for advanced, c, polymorphic, abstract, virtual
Similar
Instant
Replay Code?
- looking
for a
virtual 3D
VCR
Virtual Key
Board, Have
A Look
Microsoft
9;s Virtual
Server &
Wsus -
Localized
Microsoft
Updates with
WSUS under
Windows
Server 2003
VHD
How Do I
Virtual Pc
+web Server
+ Cms -
Setting up a
virtual
server for
Content
Management
Systems
Advanced
Network
Questions
Aef Forums -
Advanced
Electron
Forum
I Need A
More
Advanced
Screenshot
Piece Of
Software
Automate The
Advanced
Setup Of
Graphics
Cards In
Ubuntu And
Debian
Windows
Stendystate
- For the
average
user, or for
advanced IT
professional
s?
Xisto
Corporation
Launches Vps
Packages @
Computinghos
t! -
Virtual
Private
Server :
Cheap VPS
Hosting by
ComputingHos
t
Avant
Browser -
The Advanced
Internet
Explorer -
look at it,
it's
cool
Try This
Out!
Virtual
Drives For
Your
System!
Photoshop
Abstract
Signature
Tuturiol
Fedora Core
5 Under
Virtual Pc
EyeOS
Virtual
Desktop
Apache
Virtual
Hosts
Advanced
Form
Question -
Advanced
Forms
Microsoft
Virtual Pc
Is Now Free
Virtual PC
2004 Is Now
Being
Offered FREE
JavaScript:
Hide And
Show Any
Element With
CSS - From
the simple
way to the
more
advanced way
(Javascript
& CSS)
Microsoft
Live!
Local - Take
a virtual
tour
Flight Sim
2004:
Virtual
Airline
My First Try
With
Abstract
Signatures
Create A
Virtual Turd
- Wow...
Full
Abstract Sig
- Learn to
make great
Sigs
Where Can I
Learn
Advanced
Html ?
Where Can I
Find A
Virtual
CD-ROM Drive
Software ?
The Future
Of Mmorpgs -
Virtual
reality?
How-to Make
Two
Different
Abstract Sig
Backgrounds
Mambo-Invisi
on Power
Board Bridge
Advanced
Install -
IPB4Mambo
Installation
Instructions
advertisement




More Advanced C++ - Polymorphic / Abstract / Virtual example



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE