Let’s look a little closer at constructors than we did in our initial Defining Classes for Objects example.
Anytime you create an object, a constructor is called. If you overload your constructor, C++ will pick the right constructor to call, just like it does when you overload a function.
Constructors must have the same name of the class. This is how the compiler knows which function is a constructor.
The constructor doesn’t have a return type – not even void.
When you define an attribute – class level variable, you need set it’s initial value in the constructor(s), not external.
class Circle {
public:
double radius = 5; // this is wrong don't do this
}
This is not the proper way. Some compilers will give an error on this, other’s may allow it, but it is considered bad form.
class Circle
{
public:
double radius;
Circle()
{
radius = 5; // this is the way
}
};
This is the correct way, setting the value of any attributes in the constructor.
Typically a class with no parameters is included, this way you can set every attributes. If no constructor is defined, a default no argument constructor is made available, but this is considered bad form.
Class level variables are available to any method (function()) of a class. These are not global, as they should not be accessible to other objects outside of the one which holds them. i.e. I can see my radius, but not your radius. We’ll later use special methods to access this type of info.
Using Objects
You’ve already seen some basic uses of objects, but you can have some additional factors/features.
Circle circle1(10);
Circle circle2();
circle2 = circle1;
In this example, a (shallow) copy of the data in circle1 is copied into circle2, so all of it’s attributes are now the same.
Once an object name is declared, you cannot assign it to be a different type of object. i.e. a circle cannot later represent a box.
Every once and a while, you will want to create a temporary object, which is used only a single time. You can do it like in the following example:
cout << "The area of a circle with a radius of 5 units is "
<< Circle(5).getArea() << endl;
This process is called creating an anonymous object, since it isn’t given a object reference name, and it disappears as soon as it is run.
C++ Constructors was originally found on Access 2 Learn