C++
Overloading input/output operators C++
1As you might know, when we develop a simple program that runs in the system console, using the standard library iostream, we might want to have special ways of displaying a class object.
You have probably heard of the istream and ostream operators (<< and >>), we can use overloading to change their behaviour.
Since they are not functions from our class, we must use a special keyword, friend. A friend function is neither public or private, our class doesn't control it's scope. They are classes that don't belong to a class, but have access to its private members.
Let's create a simple class to demonstrate this:
class simple{ int a,b; public: friend ostream & operator < <(ostream & o, simple & s){ o << s.a << " " << s.b; return o; } friend istream & operator >>(istream & i, simple & s){ i >> s.a >> s.b; return i; } };
This class has two private members, a and b. I haven't created any constructors as we don't really need them for the example. We will change the values of a and b using the input operator >> and we will display them using the output operator <<
How the istream and ostream operators work is quite simple actually. Declaring them friend gives them direct access to private members a and b. But since they don't belong to the class we must pass them a reference to the object from the class simple we want to modify: simple & s. The other parameter is the reference to the i/o stream itself, all our modifications will be "stored" in that reference and then returned.
Let me show you a basic main to show it in use:
main(){ simple obj; cin >> obj; cout < < "\nDisplay my simple object: "; cout << obj << endl; system("pause"); return 0; }
In this sample main we instantiate simple in the object obj, and we then call the input operator >> to give a and b some values.
After that we display the values using the output operator <<.
This simple program generates the following output (Imagine I enter 2 and 3 as input):
2 3 Display my simple object: 2 3
If you want the full working code:
#include <iostream> using namespace std; class simple{ int a,b; public: friend ostream & operator < <(ostream & o, simple & s){ o << s.a << " " << s.b; return o; } friend istream & operator >>(istream & i, simple & s){ i >> s.a >> s.b; return i; } }; main(){ simple obj; cin >> obj; cout < < "\nDisplay my simple object: "; cout << obj << endl; system("pause"); return 0; }
Well I hope you enjoyed this and understood it correctly
If you have any problems or suggestions feel free to comment below,
Alex
Understanding inheritance in C++
0If you know nothing about classes in C++ you should probably go read a bit on that, although if you know Java or a similar OO language you can go ahead.
In C++, as with most modern OO languages we have encapsulation, inheritance, and polymorphism. I won't go into much detail as this is just a quick reference on inheritance hierarchy and priorities.
How inheritance works:
Skip this if you already know, I just want to make sure you can follow me here. Basically a class can inherit methods and attributes from a parent class. Why would we want to do this? Well, to avoid extra work, which is the main priority of every coder!
We will start with public inheritance. So let's start with our parent class car
#include <iostream> using namespace std; class car{ bool engine, roof; public: car(); car(int p) : passengers(p){}; car(int p,int p1); bool hasEngine()const{ return roof; } bool hasRoof()const{ return roof; } int maxP()const{ return passengers; } protected: int price; int passengers; }; car::car(){ engine=roof=true; passengers=5; } car::car(int p,int p1){ passengers=p; price = p1; }
As you can see I have added some attributes and methods as well as two constructors for testing purposes.
Each car has an engine (Or not), can have roof or be convertible (roof=false) and have different passenger count and price.
I've set the price and passengers as protected because when a class inherits from a parent class, it will be able to modify protected attributes. Although from the rest of the code they will act as private.
Now the good thing about inheritance is that we can add, modify and reuse the code from car. Let's say we want to have sports cars, which have some differences with normal cars. Let's imagine sports cars have a new attribute that is racing (true or false)
So now I will create a new class, that will inherit from car. After that we will be able to start testing,
class sportsCar : public car{
bool racing;
public:
sportsCar();
};
sportsCar::sportsCar(){
car::passengers=2;
}
Now to see what happens, let's do a simple main with a couple constructors:
(Note: This is the full code)
#include <iostream>
using namespace std;
class car{
bool engine, roof;
public:
car();
car(int p) : passengers(p){};
car(int p,int p1);
bool hasEngine()const{ return roof; }
bool hasRoof()const{ return roof; }
int maxP()const{ return passengers; }
protected:
int price;
int passengers;
};
car::car(){
engine=roof=true;
passengers=5;
}
car::car(int p,int p1){
passengers=p;
price = p1;
}
class sportsCar : public car{
bool racing;
public:
sportsCar();
};
sportsCar::sportsCar(){
car::passengers=2;
}
int main(){
car myCar(5,20000);
cout << "Normal car, passengers: " << myCar.maxP();
sportsCar ferrari;
cout << "\nSports car, passengers: " << ferrari.maxP();
cin.get();
return 0;
}
The output of this would be:
Normal car, passengers: 5 Sports car, passengers: 2
For more information on class inheritance, check out this guide by Robert I. Pitts
C++? Quick help for begginers
1Alright I've seen many people who are struggling to understand C++, students, developers... and many more. I will publish here an amazing a decent guide to get you started. I'm assuming you have "some" knowledge of programming (i.e. what is a variable, an integer... )
The basics:
If you know a little about C++, you can probably skip this short introduction. Basically C++ is a multi-purpose programming language. It is used for all sorts of applications, from simple command-line ones, to large statistical programs or videogames.
For know, you should know that you code in C++ using any editor you like, and then you must run a compiler to generate machine code (a .exe file) which is called an executable. But don't worry about that yet.
Starting up: "Hello world!"
Enough of the boring stuff, let's get started doing some real stuff. For now I recommend you download a source code editor, like Dev-C++.
First steps in Dev C++:
- Install and open the program
- Close the Tips that will open up
- Go to File > New > Source code (Or click Ctrl+N)
You will now see an empty page where we will write our code
Base structure:
Our C++ programs will always have the same base structure for now: First we will include necessary files (I will explain later on what they are), then we will declare our functions, and then will go the main code.
So first things first, we will include the necessary files. In order to display on the screen "Hello World!" we are not going to set up an interface, that's more advanced stuff. We will be using the system console (Yes, that black thing with white text on it). The file that will allow us to do that is iostream. So our first line will be:
#include <iostream>
Now that we hace access to the input and output functions, we will tell the compiler that all functions we use are from there, we do that by declaring a namespace:
#include <iostream> using namespace std;
And that is all we need in the header. We can now move on to the main code. In C++ the program executes always the code found inside a function called main. Whether you are on Linux, Windows, Mac, or other OS, it will be of one type or another. For Windows users it will be int
So let's set up an empty main for now:
#include <iostream>
using namespace std;
int main(){
return 0;
}
And finally the Hello world code, we want to display it on the screen, and the function for that is cout (If you are a programmer in other languages, equivlents would be echo or printf)
We must remember to add a "pause" after we display the message, to leave the console open. If we develop in a Windows environment, we can use the command system("pause"); but I recommend using a more global solution like cin.get();
So the final program would be:
#include <iostream>
using namespace std;
int main(){
cout << "Hello world!";
cin.get();
return 0;
}
And this finishes lesson 1
In our next tutorial I will teach you the use of variables and a more advanced look at the iostream functions cout and cin