NOTE,tutorial,supposed,teach,classes,operator
Quick Search for:  in language:    
NOTE,tutorial,supposed,teach,classes,operator
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
C/ C++ Stats

 Code: 451,578 lines
 Jobs: 605 postings

 
Sponsored by:

 

You are in:

 
Login



Latest Code Ticker for C/ C++.
Visual Pi Hex
By jo122321323 on 8/25


Click here to see a screenshot of this code!ShortCutSample
By Massimiliano Tomassetti on 8/25

(Screen Shot)

AnPMoneyManager beta
By Anthony Tristan on 8/24


A calculator (english/polish )
By Tom Dziedzic on 8/24


MMC (Mouse Move Counter)
By Laszlo Hegedüs on 8/24


Text-DB
By Jerome A. Simon on 8/24


JDos
By Jerome A. Simon on 8/23


Game 1945X
By Ozgun Harmanci on 8/23


Find hidden "back streamed" files on NTFS partitions. This code is a must for sec consultants.
By Israel B. Bentch on 8/22


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



 
 
   

Intro To C++ classes, operator overloading and inheritance

Print
Email
 

Submitted on: 5/6/2000 4:38:27 AM
By: Martin Hristoforov  
Level: Intermediate
User Rating: By 8 Users
Compatibility:C++ (general)

Users have accessed this article 12419 times.
 
(About the author)
 
     This tutorial is supposed to teach you how to do classes, operator overloading, and inheritance. NOTE: You need to have a good knowlege about structures.

 
 
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.

NOTE: Please put #include < iostream.h> at the beggining

If you're reading this then I guess that you want to learn some more about classes and some of the goodies that come with them.

NOTE:This is a lenghty tutorial.

Now first we are going to create a class. We'll call it OurClass because it is ours :). Here's the code:

class OurClass
{
private: // optional but it is more readable that way
int number1;
public: // not optional
OurClass() : number1(0)// Constructor
{ } // nothing in here but feel free to add whatever you want
OurClass(int num): number1(num)//Constructor with arguments
{ }
void set_number(int num)
{ number1 = num; }
int get_number()
{ return number1; }
}; // don't forget the ; at the end of every class

This is our basic class from wich we are going to do everything else. You should notice the Constructor. This is a very usefull feuture because it lets you set the class variable(s) value(s) with it just like you would in a structure for instance. The constructor is basically an overloaded function so you should use it as you would overloaded functions. In our case if there are no arguments then number1 will be set to 0, and if an integer is passed then number1 will be set to the passed value. Lets see out how main goes:

int main()
{
OurClass oc1;
OurClass oc2(10);
cout << oc1.getnumber() << endl << oc2.get_number(); // returns 0 in the first line and // 10 on the next one
oc1.set_number(100);
cout << endl << oc1.get_number(); // shows 100
return 0;
}

Easy eh? I tought so. See, using classes is esentially the same as using structures with the only difference being that you can have functions in them wich you use just like ordinary functions but with classname and a dot before the function name(you need to declare it first just like you would declare a structure.) You don't have access to the protected variable(s) in the class so it is essential to use class functions if you want to change any of those values. You can however declare the class variables as public instead of private but this is kind a pointless since one of the major ideas if classes is data hiding.
Next thing we should do is overload an operator. Let's overload the ++ operator. All we gotta do is write one new functions in our class. The function code would be (this should be added inside the class):

OurClass operator ++ ()
{
++count;
OurClas temp;
temp.count = count;
return temp;
}

To see what happend let's make main looking like this:

int main()
{
OurClass oc1;
OurClass oc2(10);
cout << oc1.getnumber() << endl << oc2.get_number(); // returns 0 in the first line and // 10 on the next one
oc1.set_number(100);
cout << endl << oc1.get_number(); // shows 100
oc1++; cout << endl << oc1.getnumber(); // Now we get 101
oc2 = oc1++ ; cout << endl << oc2.getnumber(); // Getting 102
return 0;
}

First off you need to use the operator keyword when overloading operators. In out case we don't need any arguments (the ++ and -- operators are the only ones that don't need arguments.) So when we say classname ++ we are basically calling the function ++ in classname and do what we need acordingly.
Now lets overload the + operator wich is a little bit harder. The code for the class will be (add it to the class):

OurClass operator + (OurClass second)
{
int answer = number1 + second.number1;
return MyClass(answer);
}

Please note the return. Let me clarify, we are basically defining a new class, we put 10 in the parentless with wich we are calling the constructor so we return a class in wich the number1 integer is set to 10 (yes you can do this kind of stuff :).

Main will look like:


int main()
{
OurClass oc1;
OurClass oc2(10);
cout << oc1.getnumber() << endl <<
oc2.get_number(); // returns 0 in the first line and // 10 on the next one
oc1.set_number(100);
cout << endl << oc1.get_number(); // shows 100
oc1++; cout << endl << oc1.getnumber(); // Now we get 101
oc2 = oc1++ ; cout << endl << oc2.getnumber(); // Getting 102
OurClass oc3;
oc3 = oc1 + oc2; cout << endl << oc3.get_number; // It should be 203
return 0;
}

Now you may ask what the hell happend? Well, it's actually pritty easy. Remeber when I told you that when you write classname ++ you are basically calling the ++ function in the classname. Well this is the same with the difference being that you say classname + classname2. So classname2 is the argument. See how easy it is? Read the note.

NOTE: classname - this is the class in wich the function + will be executed. The function name can be +. -. *, /, <, >, % and all other operators (my guess will be that you could even overload the AND(&&),OR(||) and NOT(!) ones. classname2 - this is the class wich is sended as an so you would need to use classname2.

I hope you understood that one. You can overload operators for various things. For instance check out the string.h header and look at the code. You'll see one way to put it in a good use. Next we are going to do some inheritance. So how do we do it? Well it is easy. First we will add 2 lines to our class, those lines will be( just after the the:

private:
// optional but it is more readable that way

int number1;) :
protected:
int pnumber;

So then we are going to make the derived class. We are going to call it Derived. Here is the code:

class Derived : public OurClass
{
private:
// you can put variables in here but we won't do that in this tutorial
public:
Derived(int num) : pnumber(num)
{ }
int get_derivednum()
{ return pnumber; }
void set_derivednum(int num)
{ pnumber = num; } };


Let me try explain what the hell just happened. First of all we added the:

protected:
int pnumber;

OurClass (wich we should now refer as our BaseClass.) Protected is essentially the same as private with the only difference being that you can access this variable from the derived class, where you cannot access the private variables. So the derived class is a class that inherits all the functions of the base class and you can also add new functions to the derived class(and variables). So for instance if we have a class that describe a human being we could put in it stuff like height, eye color, hair color, and all the feutures that are the same between a man and a woman. So then we could make 2 derived classes, one for a man and one for a woman and in it we could put only the characteristics that are special for each one(like genitals or something.) Anyway, lets see out main (I created a new main so you don’t get confused with all the previlious stuff).


Int main()
{
Derived d1;
d1.set_derivednum(145); cout << d1.get_derivednum() << endl; // Those are the basic functions that are no different than the functions in the BaseClass
d1.set_number(10); cout << d1.get_number() << endl; // Here we are using the //base class functions return 0; }


So this outta make it quite clear. A derived class has all the so-called traits of the base class plus it’s own traits (traits are the functions and the variables). To use a variable from the base class when you’re in the derived class you need to get it as protected or as public. Declaring the derived class is made with: Class DerivedClassName : public BaseClassName This is how it’s done. If you don’t understand it then feel free to go and grab a book with a better explanation(I tried making this stuff as short as I could and if you get a book then you will read a lot more). So if you liked this tutorial send me an e-mail at mhrist@earthlink.net and I will try get more tutorials on the fascinating world of c++.

Martin


Other 1 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
5/6/2000 2:00:00 PM:Ian Ippolito
Well done tutorial, Martin!
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/7/2000 6:33:57 PM:Pachunka
Awesome man.. been lookin' for this.. been stickin' to C 'coz I was afriad of C++ classes.. had no idea 'twas so simple.. thanks :P
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/14/2000 5:15:50 AM:Thomas
Your code is good but there is a few point which l like to make. 1) If a function only return value and nothing else, is good to make them a constant type like function() const; 2) For the variable name, why not try FisrtNumber, SecondNumber and use a typedef to shorthen it to 1, 2. 3) Is the convention that public function call for private data memeber, l think it is a good practise to follow the convention. 4) Why no try to make the function inline, it will be clearer to the reader and for the programmer too. Bye
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/14/2000 5:46:20 AM:Martin
1) There is no point of trying to load the readers with information that isn't that important or valuable like the const stuff. 2) I like number1 better and I didn't used typedef because it is only one variable and again: no need of excessive and non-related stuff. 3)Don't know what convention you are talking about (maybe I am not reading it right) 4) For the inline functions it is a good idea but I don't like using them and besides there may be users that doesn't know what are inline functions and how they work and we don't want people to start using them all the time and not knowing what they are doing, do we? Bye
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/14/2000 7:49:46 PM:Thomas
Hello, it's me again. l read your message and about the convention thing, l think you are right. l am wrong, so, sorry about it. and l hope you can accept my apology. Thanks for pointing my mistake.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/8/2000 9:06:11 AM:gaurav
I am highly impressed by your articles would you please allow me upload them at my website www.gauravcreations.com If you wish you can also submit me all other programs/tutorials that you have made
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
10/18/2000 5:10:07 PM:Greg
Hey, just one quick point that I noticed in the very beginning on your first example, you create a function called get_number , you have a small typo on the first part of you code though you have cout << oc1.getnumber() << endl , just to let you know and others that may not notice it :). Greg
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/30/2001 5:19:59 AM:Ashik
It is really very good - That too for beginners it is very easy to pick up .
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
9/15/2001 4:21:57 PM:The Wedgie
Hope you don't mind, but there are several errors with your code which I would like to point out for the benefit of anyone who will read it: OurClass operator ++ () An operator++ returning by value. Guaranteed to cause problems when you least expect it. Consider the following: ++(++a); Does this increment a by 2? No. First, a is incremented by one and then a copy of a is incremented by one. Result is that a only increases by 1, not the expected 2. Oh dear... What you want is this: OurClass& operator ++ () Returning by reference solves all your problems. General rule is that if the operator modifies the object, return by reference, otherwise return by value. For example, an operator+ would always return by value. Int main() This is obviously a typo, but someone will go and type it in regardless, so I thought I should point it out...
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/5/2002 1:24:24 PM:Alfred Torres
I'm finishing up my first bachelors degree in computer science and I'm over 30. I just want to say; that I really appreciate the way this program was presented; it has been a tremendous help to me. Planetsourcecode has been a real lifesaver for me. Thank you.
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.