Classes & Objects

Object Oriented Programming is a different approach to writing programs than previously seen in our C Programming Guide. The fundamental ideas we will look at are the class and the object.
You can think of the class as a more advanced struct we learned in C.
If you recall, in C we declared a struct for complex numbers like so:

struct Complex{
int real;
int imag;
};

In C++, an object oriented language, we would define Complex as a class, opposed to a struct.
Let’s look at the key differences.

class Complex{
int real;
int imag;
};

The 2 “items” inside our class, the real and imaginary integers are called the data members of our class.
We can make Complex numbers in our main function like so:

class Complex{
int real;
int imag;
};

int main()
{
Complex A;

return 0;
}

When we declare a variable of the class, this is called making an instance of Complex, or instantiating the class. The variables of the complex class are called objects.
The relationship between a class and its instances, or objects, is referred to as a is-a relationship.
Above, in our example, we created a complex object called A, you can say that: “A is a complex”.
The relationship between a class and its data members is a has-a relationship.
Observe the data members of the complex class are the int real and imag. You can say that: “Complex HAS an imag and a real”.
Now, let’s try to access real and imag in main, and set them to some desired values.

class Complex{
int real;
int imag;
};

int main()
{
Complex A;

A.real = 2;
A.imag = -3;

return 0;
}

If you run this code, you will see that you get an error.
What is the problem?

We will look into this in the next section, it’s one of the key features of Object Oriented Programming and is called Abstraction.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s