tutorial,request,explaing,classes,talks,inlin
Quick Search for:  in language:    
tutorial,request,explaing,classes,talks,inlin
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
C/ C++ Stats

 Code: 481,463 lines
 Jobs: 1,069 postings

 
Sponsored by:

 

You are in:

 
Login



Latest Code Ticker for C/ C++.
SQL 'LIKE' clause clone in C
By José Luis Gallego on 10/19


Determing File Version, System Language and Memory Status
By Ixac on 10/19


How to create custom messages
By Xeron on 10/18


DeathBrain
By DeathBrain on 10/18


Click here to see a screenshot of this code!A C++ Tutorial for Complete Beginners #2
By Jared Devall on 10/18

(Screen Shot)

Click here to see a screenshot of this code!_PAGE REPLACEMENT ALGORITHMS (FIFO)_
By ENRICO X on 10/18

(Screen Shot)

extract file from resource and write it to disk
By cpsim on 10/18


Click here to see a screenshot of this code!CurrencyConvert er 2002
By Xeron on 10/17

(Screen Shot)

File Saver/Opener
By Jek on 10/17


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!





Affiliate Sites



 
 
   

Classes, Inheritance, Constructor Polymorphism, Pure Virtual Functions, ADT's and More!

Print
Email
 

Submitted on: 3/3/2001 3:30:34 PM
By: Jared Bruni  
Level: Intermediate
User Rating: By 15 Users
Compatibility:Microsoft Visual C++

Users have accessed this article 13028 times.
 

(About the author)
 
     This tutorial was a request on explaing classes. This talks about the inline keyword, polymorphisim, inhertiance, mulitple inheritance, function overloading, Abstract data types, pure virtual functions, and more!

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
OOP with C++ using classes, and inheritance

This was a request I got on writing a tutorial on using classes. I know there are already a lot of really great tutorials here on planetsourcecode, but alot of people think I can explain things really well. So I might as well give it a shot, here we go:


Part1: Intro
When attempting to express mind to machine there comes a time when using standard structured programming techniques just gets to heckteck and messy. This is normaly only when writing larger programs, that require quite a massive amount of code. To help with this, C++ language implements what are called classes. Classes feature the almighty concept of encapsulation. What encapuslation basicly is, we have the ability to write code once and 'encapsulate it'. This means that we can create objects that function in many different ways but the actual inner workings of this code are hidden to the person applying it. Its like you can use the code, but you dont have to know how it works. How this is accomplished is by creating a class. Classes stand as a specific type, and when a Instance of this type is made it is called a Object. Objects resemble real life objects more then functions and other ways to express your ideas. They have a birth (constructor) a death (deconstructor) and have the ability to pass on there knowledge to there offspring (inheritance)

IF your a C programmer, THEN you are most likey familar with data structures (C/C++ keyword struct). This is basicly a type of variable, that holds many different varaibles within it. The expansion of the struct, the class is like a struct , however it is not limited to simply variables. Within it can exisit functions (methods), which can manipulate the data within the class. You can set certin areas of the class, as public, private, and protected, to ensure that the person using the code, cant get into the wrong spot and mess things up. The coolest thing I thing about classes is, that they can be used so much better to describe physical objects that reside within space. Like I think thats its much easyier to make a object and encapsulate its functionality, then to attempt to pass a pointer to a structure from multiple functions. Yes, the C style way may cause less overhead,and when you dont need classes I suggest you use this method, but when it comes down to trying to keep your code readable and editable classes are a savior. When you encapsulate a object, before you begin to use you can perfect it, and ensure every aspect of it works perfectly, and once you know it works perfectly then its just a matter of applying it. This can greatly help the debugging process, and help you cut down , were a error could possibly be occouring at. Now that this is said, lets begin to take apart creating a class


Code Snippet:

class Jared
{
int x;
int y;
public:

Jared(); // constructor
~Jared();// deconstructor
void SetCord(int x, int y);
};


Jared::Jared()
{
}

Jared::~Jared()
{
}


void Jared::SetCord(int ix, int iy)
{
x = ix;
y = iy;
}



Now what we did, was use the class keyword, and then followed after the keyword is the name of the object. Then within the { }; (block) is were you declare the variables and the functions/constructor/deconstructor. The function prototypes are within the block, and then the function bodys, are outside of the class declare just as normal, the only difference is the name of the class and :: come before the functions name. The constructor is called when the class is created, and is used to initlize data. The deconstructor is called when the class is destroyed and is used to delete, or deinitlize data. Also note, you dont have to put the function bodys, outside of the class. Using the C++ keyword inline , you can directly embed the function within the class. However this should only be used when you have only a few lines of code. Since when you use inline it directly imbeds your code were they called the function, rather then jumping to some area of memory were it is at. Heres an example of that class, using inline.

class Jared
{
int x;
int y;
public:
inline Jared()
{

// constructor
}
inline ~Jared()
{

// deconstructor
}

inline void SetCord(int ix, int iy)
{
x = ix;
y = iy;
}

};



Now lets talk about the public,private,and protected members of the class. Classes in C++ are by default private. There for, everything after the keyword public: is see able by the user when they create an instance of this class. In C++ a struct is the same as a class (it can also have members) the only difference is by default it is public

To make an instance of this class it we would do the following

Jared ImJared;
ImJared.SetCord(10,10);


What this would do , is create a new instance of the class, name ImJared. Then we would invoke the SetCord method within jared, and set the private values x,y to 10.

Talking about static class members

There comes a time when eventuly your going to need to use static class members. Basicly what a static class member is, is a variable/function that is the same through all instances of the class check out this example.

class Jared
{
static int count;
inline Jared()
{
count++;
}

};



Jared ImJared;

Jared ImJared2;

Basicly what happens, is every time a new instance of Jared is created with memory (on the constructor), it increments the count variable. Now we have a index of how many instances of the class (called objects!) are currently stored within memory. This is pretty neato now, lets dive head on into what makes classes rock so much.

Part2:

Inhertiance Abstract Data Types (ADT's) pure virtual functions,function overloading, and function/constructor polymorphism

When writing classes, there comes a time, when there is a generic part of the class, that you would want to use over and over. Like say your creating a class hierachy of the life. You would have a class for the basic life form, and then a expansion of the life form for the animal, and then a expansion of the animal for the human. Rather then writing the same basic functions that each one would share over and over, what we can do is created a base class, and then 'inhert' this information into are new classes so that they can share the same methods. This is really awesome, and once you get the hang of it, it can help your code so much you will be amazed. What is an abstract data type? A abstract data type is basicly a class, that contains what are called pure virtual functions. Another name for a pure virtual function (that makes sense) is a NULL function. It is basicly a prototype defenition of a function that equals 0. This allows us to create the outline structure for are classes, and then have the classes that inhert override (function overloading) these methods. You cannot initlize a Abstract Data type. It must be inherited and have its pure virtual methods overloaded/overrided. What is function overloading? Function overloading is when you inhert something from another class, and want to get rid of a specific function. You can 'override' it in the new class, and then your new function will be used instead. What is function polymorphsim? Polymorphisim basicly means many forms. We can have functions or constructors with the same name, and then pick out different parameter lists, so they user has an option of which one they wish to use. This is really useful and is really awesome! Now lets check out a example using these concepts

Example of Constructor Polymorphism

class Monkey
{
int monkey_x;
int monkey_y;

// default constructor
inline Monkey()
{
monkey_x = 0;
monkey_y = 0;
}


// different constructor (polymorphsim)< // br> inline Monkey(int x,int y)
{
monkey_x = x;
monkey_y = y;
}


};

Initlizing this object


Monkey Jared; // initlize with default constructor

Monkey Jared2(100,100); // initlize with different constructor

pretty neat ehh?

Now lets talk about ADT's and using an ADT with inhertiance


class theADT
{
public:
int x;
int y;
virtual void Jared() = 0; // pure virtual function (null function)

};

class OnTop : public theADT
{
virtual void Jared() { }

};

Basicly what we did was create a base class (ADT) containing a NULL (pure virtual function). Then what we did was inhert this class into a higher level class, and overloaded the pure virtual function so that we can initlize this object.

Multiple Inheritance

Multiple inheritance is the ability to take a array of classes, and combine them into one. Your classes are not limited to just inherting from one other class, like a few other high level languages which I wont talk about (cough* cough* java). Mulitple inheritance is a very important aspect of good solid OOP code, and I think without it, the language is a crutch. Interfaces bite

Example of multiple inheritance


class This1
{
public:
int x;
int y;
};


class This2
{
public:
int w;
int h;
};


class Object : public This1, public This2
{
inline void SetCords(int ix, int iy, int iw, int ih)
{
x = ix;
y = iy;
w = iw;
h = ih;
}

};



What did we learn

C++ is power. C++ allows us to adquetly express thoughts in the form of objects. This is much more dynamic, and makes programming much more potent. There is nothing better. Objects resemble objects, that reside within physical space better, and are a very key ingredient in the C++ language.

Check out my portfolio for many many examples on all this wonderful stuff. If you need any help or have a request for a example, Im still taking them so dont be shy, go ahead and mail me.


"programming mastery comes with patience and pratice, not acceptance from others"

Code on my friends,
Jared Bruni


Other 278 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
4/14/2001 12:59:40 AM:Bonk
Hey seksy how you like my blue hat ??lol nice work Jared ;0)
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/15/2001 5:29:09 PM:Faraz Hussain
I would like to point out the technically wrong terms in the article.In the part 1 after the code snippet ,the writer writes
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/15/2001 5:40:40 PM:Faraz Hussain
i would like to point out some technically wrong terms in the article .In part 1:intro after the code snippet the writer writes "There for, everything after the keyword public: is see able by the user when they create an instance of this object" but it is technically wrong,it should not be "an instance of this object" rather it should be "an instance of this class". The second mistake is where in part 1 the writer writes "Now we have a index of how many classes are currently stored within memory. " but it should be "Now we have an index of how many objects of the class Jerad are currently stored in memory".
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/23/2001 8:40:08 PM:Jared Bruni
I am not exactly an english proffesor :). However I have changed the words to suit the standard of what we call the concepts I was trying to explain.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/23/2001 8:40:44 PM:Jared Bruni
can anyone say " we dont need no education ? "
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/23/2001 8:43:37 PM:Jared Bruni
Since were on the topic of spelling errors, you spelled the name of the class wrong. Its Jared not Jerad
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/5/2001 12:27:33 PM:Jared Bruni
I have however fixed the spelling errors, and thank you for pointing them out.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/5/2001 12:31:16 PM:Jared Bruni
"twist and shout"
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
11/3/2001 2:49:26 PM:KingZumby
Thx jared for this tutorial, it has increased my edumacation on c++. i hate talking like this but the f*** sensor will not let me post. so i have to be happy happy happy *ARRG!* it was good, i gave u 5 stars
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/11/2002 6:52:25 AM:barkhadle
so, i have to be happy,it was good. jered tutorial, it has increased my knowledge
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | C/ C++ Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.