Once you create your class, you need to create an object. The Class is just a blueprint for the program to follow. It doesn’t do anything until you create an object based off of that blueprint.
Think of a house. If you have a house blueprint, all you have are some sheets of paper or a computer file. You can’t live there, as it’s just a design specification. It’s not until the house is built that you can move in and live there.
The exact same thing with a Class. You can’t use it until you create an object with it.
To create an object is fairly easy. Assuming our Circle class from our previous example, we could do something like:
Circle circle1;
Circle circle2(20);
Circle circle3(3.75);
Notice that Circle becomes the data type, and the name of the variable is passed the optional argument. The first variable, which doesn’t have a value passed to it, uses the default value found in the overloaded constructor.
To call the object’s methods, we would need to reference it like below:
cout << "The area of the first circle is: " << circle1.getArea() << endl;
cout << "The area of the second circle is: " << circle2.getArea() << endl;
Notice that we specify the object name, circle1
for example, then a period and then the method which we want to call.
Since our attribute, radius, is public, we can do something like:
cout << "Circle 2 has a radius of " << circle2.radius
<< "which means that the area is " << circle2.getArea() << endl;
Notice that the attribute is just the attribute’s name. Not parenthesis are needed since it’s not a function (method technically because it’s an object) call.
In both attributes and methods, they are unique to that object. Just because there are other objects with the same names for attributes and methods, does not mean that they are interchangeable. This is why when you call for the getArea() method, it looks at which object, and uses that object’s radius.
Think about our student example from before. A classroom my be full of different students. While they could all be represented by the same Class, each instance is totally unique. You are different from the person sitting next to you, which is different from the person several chairs over. Your names, student numbers, etc are not interchangeable. Even having some of the same attribute values doesn’t make you the same, each individual is unique in real life, just as you would be in a computer system.
Creating an Object was originally found on Access 2 Learn