We can add a simple print member function to check if constructor works properly:Ĭout << "First name " << firstName << endl Ĭout << "Last name " << lastName << endl Ĭout << "Year of Birth " << yearOfBirth << endl
#TUTORIAL CONSTRUCTOR GAME CODE#
Once this line of code will be executed, you will see the following output:Ĭonstructor with 3 parameters is starting We pass parameters right after we have declared an object. In this case, you don’t need to call constructor explicitly. You are passing parameters to the constructor after declaration in the same way as you call a function with parameters. Notice that parentheses are used after object declaration. Now you can initialize objects of Person class once they are created: set data members according to the parameters Person::Person(string fName, string lName, int year)Ĭout << "Constructor with 3 parameters is starting" << endl This is an example of a constructor with three parameters for Person class: To create a constructor with parameters you have to specify its parameters in the parentheses as we do to specify parameters of a function. The constructor with parameters can be used to initialize data members of the object. In above statement, Default constructor will be called and you will see the following output:ĭefault constructor can be used to prepare some resources or for allocation of memory before you will start working with an object. Now we can declare an object of a person class: Here is an example of a default constructor for Person class:Ĭout << "Default constructor is starting" << endl For example, if you want to create a constructor for Person class from the previous topics:Ī default construct is a constructor, which does not have any parameters. A constructor is a special function that is called every time you create an object.Ī constructor is a public member function that has the same name as the name of the class. C++ offers a special function, called constructor, which makes the initialization of an object. As you know, private and protected data members can be accessed outside the class by using public member functions of the class. When you create an object, you need to initialize its data members.