C++ Class Constructors
Learn about C++ Class Constructors and how to use them
Overview:
A constructor is a special member function of a class, defined the same way as other methods of a class. The constructor is executed whenever we create new objects of that class, which consequently makes it the perfect place to initialize the class’ member variables. Also, it is important to note that a constructor needs to have the exact same name as the class and it does not have any return type.
Default Constructors:
The following is an example of class declaration including a constructor declaration.
class Book {
private:
string title;
int year;
double price;
public:
Book();
} book;Book::Book() {
title = "The Martian";
year = 2011;
price = 9.99;
}
Like any member functions, a constructor has access to it’s member functions and variables. The main function of a constructor is to initialize the member variables of a class object. Meaning, if you create an object of the class Book
, the new book will always be “The Martian” with it’s values declared above as the default object. You can call the default constructor as follows in your main function:
Book book_1;
Overloading Constructors:
Constructors can also be overloaded with parameters, which creates different versions of the function depending on the number of parameters. The compiler will automatically call the constructor whose parameters match the arguments. A Book
constructor function, with all the required arguments would look like:
Book::Book(string newTitle, int newYear, double newPrice){
title = newTitle;
year = newYear;
price = newPrice;
}
Now, when you declare a new object of the Book
class, you can assign values at the time, to populate your object with values as such:
Book book_2("The Power of Habit", 2012, 12.00);
In a nutshell:
A constructor is a member function in a class that has the same name as the class and has no return type. A constructor executes when we create an object of a class, and can be used to initialize the member variables of the class. A constructor can also be overloaded with parameters to create multiple versions of it.