Menu

Object Oriented Programming

Object Oriented Programming (OOP) is a different approach to writing programs than previously seen in our C Programming Guide. This first post on OOP will focus classes and the objects.
You can think of the class as an improvement on the 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:

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 an 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.