Object oriented programming is one of the perks to C++ (and Java). This tutorial is about data structures. Data structures are a great introduction to object oriented programming. I will go more in depth into OOP in later tutorials. This is part 19 of my C++ tutorials. If you want to check out my other tutorials in this series, here they are:
Part 11: Colored Text in your Terminal
Part 16: Binary, Bitwise Operators, and 2^n
A data structure is basically just what it sounds like. It is a clump of code designed to be a structure for something else. Here is how to declare a structure:
struct name
{
//members go here
} /* object names go here*/ ;
Here is a more specific example:
struct employee
{
string name;
int id;
float pay_rate;
} fred, bob, susanne;
First, you can also declare objects later in main() like this:
employee fred, bob, susanne;
To initialize the members of the structure, type in the object name, a period, then the member name. Here is an example with fred:
fred.name = "Fred";
fred.id = 12345;
fred.pay_rate = 7.25;
This can be done with all of the objects that were initialized. Each object has its own members (fred.name is different than bob.name).
You can also pass objects to a function. Here is a program I wrote that does that:
#include
#include
using namespace std;
struct animal
{
string name;
string color;
int num_legs;
};
void printA(animal a)
{
cout << a.name
<< "s are "
<< a.color
<< ", and have "
<< a.num_legs
<< " legs.\n";
}
int main()
{
animal dog, bird, spider;
dog.name = "Dog";
dog.color = "brown";
dog.num_legs = 4;
bird.name = "Bird";
bird.color = "green";
bird.num_legs = 2;
spider.name = "Spider";
spider.color = "black";
spider.num_legs = 8;
printA(dog);
printA(bird);
printA(spider);
return 0;
}
Here is the output:
[cmw4026@omega test]$ g++ animal.cpp
[cmw4026@omega test]$ ./a.out
Dogs are brown, and have 4 legs.
Birds are green, and have 2 legs.
Spiders are black, and have 8 legs.
[cmw4026@omega test]$
I hope this was simple enough! Leave suggestions in the comments.