Simple OO demonstration in C++, comparison to Python
Archive - Originally posted on "The Horse's Mouth" - 2013-07-01 11:12:43 - Graham EllisFrom last week's quick introduction to C++ (a private course - half a day added on to the end of a C Programming course - an example of how C++ implements objects for a newcomer to C++ who's seen some Python.
Firstly, in C++ you must predefine the API - the interface between the user and the class. And also the member variables and methods of each object type too:
class train {
public:
train(char *, int, int) ;
int getpeeps();
private:
int length;
int seats; };
Methods are defined in a similar way. In C++, there's no need to declare the object variable as a parameter (in fact you must not do so), but in the other hand you need to declare the class name on the front of each method. And the constructor is a method with the same name as the class. So:
train::train(char *dest, int length, int spc) {
this->length = length;
this->seats = spc; }
int train::getpeeps() {
return (int)(this->length * this->seats * 1.4); }
Now for the application. You can create objects in several ways in C++; I chose to use the new keyword as it allocates memory on the heap in a similar way to Python allocates memory to objects
swindon = new train("Swindon",5,83);
cheltenham = new train("Cheltenham Spa",1,75);
And I can access that data via an object method.
cattle = swindon->getpeeps();
cout << "can take " << cattle << " to Swindon" << endl;
cattle = cheltenham->getpeeps();
cout << "can take " << cattle << " to Cheltenham" << endl;
If you prefer the "." notation of Python, I could replace
cattle = swindon->getpeeps();
with
cattle = (*swindon).getpeeps();
but that gets messy.
Complete C++ source code [here].