1. Home
  2. Training Library
  3. Programming
  4. Programming Courses
  5. Introduction to Classes and Objects in C++

Constructors and Destructors

Contents

keyboard_tab

The course is part of this learning path

Start course
Overview
Difficulty
Intermediate
Duration
1h 36m
Students
16
Ratings
5/5
starstarstarstarstar
Description

Ever wondered how they maintain all the data and behaviors for the items in your inventory in a video game? Or maybe you've thought about how super-complex complex systems like banking systems, store management software, automotive digital diagnostic systems and tons of other applications were built? There's often a good chance that many of these applications use some form of Object-Oriented Programming. In this course, we look at Object-Oriented Programming, focusing on objects and classes.

Learning Objectives

  • Understand how classes are designed and constructed and how objects are created from them
  • Explore both the data members and member functions from which we build classes
  • Learn how to instantiate classes as objects
  • Learn how to use a rectangle class and a book class together and test them out

Intended Audience

  • Beginner coders, new to C++
  • Developers looking to upskill by adding C++ to their CV
  • College students and anyone studying C++

Prerequisites

To get the most out of this course, you should have a basic understanding of the fundamentals of C++.

Transcript

In the last lecture, we saw how we could modify our classes so that the specification and implementation are in two separate files. In this lecture, we're going to discuss Constructors and Destructors. First, we're going to add a constructor to our house class. Constructors, just like any function can be overloaded and can take 0, 1, 2 or any number of parameters. Their syntax is similar to other functions, but they don't have a return type at all. Not even void. Also, constructors must have the same name as the class. Destructors also have the same name as the class and a tilde in front of them. There can only be one of those and they're called when the object goes out of scope or is reclaimed. We'll talk about those later. To create an object from any class, there must be a constructor. We haven't written one yet, so the compiler actually does create one for us with no parameters called the default constructor. So, continuing with our Houses project, which I will open. Inside of our house class, we need to add a constructor that takes no parameters and sets the default values for number of stories, number of windows and color. Note that there is no return type whatsoever. So, I'm going to add to the .h, I need to add House right there. So, that's pretty simple. That's the first part. And now, inhouse.cpp. Traditionally we add it to the top. You still need House and the scope resolution operator and then the name of the function in this case, House and also the body. We're going to say this numStories is = 1 by default, the number of windows is = 4. And we'll say, oops, that should be an error of course. And then we're going to say that the color is white. So, many programmers would actually look at this and say that I've added my own default constructor. In fact, that's a very common term to use for any constructor that takes no parameters like this one. However, technically, the default constructor is the constructor that the compiler provides you with only if you do not explicitly write any constructors yourself. What we've written here is actually called a no argument or simply no arg constructor. Pretty simple, right? Now, if I were to print the values of these before I changed any of them using the setters and main, let's see what happens. So, I'm going to go into main and we're going to call the print on myHouse before any of the setter calls. So, myHouse is right there, that's where we do the setting. So, I'm going to say myHouse.print. All right, very good. So, let's see if this constructor worked. And as expected, we will get that the house is white and has 1 stories, obviously, the grammar is wrong here, and 4 windows. So, that is the default. That is the absolute default that is created when we create our house objects. So, 1 storey, 4 windows. Awesome. Pretty cool. So, the constructor is called automatically when the object is created or as we might say, constructed. Now, what about destructors? The destructor is called on an object when it goes out of scope, which we learned about earlier in the course. For our purposes with the House class, the destructor isn't super important because we haven't allocated dynamic memory, which we will talk about later in the course. Then destructors will become incredibly important for cleaning up after ourselves. For now, it would be awesome if we could just see one in action, just to see what it does, right? So, let's write one. So, I'm going to add a destructor to the .h file. Oftenly, we put it right below the constructors. So, just like the constructor, but it has a tilde in front of it. That's the standard keyboard that we use here in America, that is above the tab. Alright, so over here, now this is going to be a little bit weirder than you might expect. So, we have the scope resolution operator after the class name and then tilde, and then the name of the class which gives you the the destructor. So in here, we're just going to put the... and then color house with numStories stories. And now on the next line, I'm going to put "and" numWindows, "windows is being destroyed." All right, here we go. So, let's rerun the application. Let's save this just to make sure, and rerun the application just to see what it does. So, we rerun the application here. We'll go back to main real quick here and bring that back. So, it says, this is during the construction, right here. So, the house is white and has 1 stories and 4 windows. That was from our initial print before we did the numStories and setWindows and setColor and things like that. You'll notice the other two are just from where we have set the number of stories, windows, and color on each of the house objects right here. Now, there really are only two house objects. So, after they go out of scope, the destructors are called. Now, I forgot to put an extra space here between the number and stories, which maybe we'll go correct real quick. So right there, that was missing. We run it. Let's see what it does. There we go, a little bit better. So, the blue house with 3 stories and 10 windows is being destroyed, and then the red house with 2 stories and 6 windows is being destroyed. I see an extra space there, we'll fix that, but no big deal. We get the point. When they go out of scope, the destructor is called automatically. When it's created, when the object is created, the constructor is called automatically. Awesome. Alright. So, that's pretty cool. Immediately before our program completely terminates the lifetime of our objects myHouse and your house expire. So, the destructors are called automatically when that happens. Just like a constructor is called automatically when an object is created, the destructor is called automatically when the object is destroyed. That is, when it's memories return to be used for something else. One important note is that while we can have as many constructors as we want with different overloads, just like any other function, again, I have to stress there can only be one destructor. It never takes a parameter. And that's a good segue into our next challenge. I'd like you to add a parameterized constructor that takes three parameters; One for each of the three data members. And I want you to set them inside that constructor. Then try to see if you can figure out how you might test your new constructor by creating a third house object in main. The big hint I'm going to give you is, when you declare the object, it might look a little bit different, it might look kind of like a function call. So, pause the video and try to work on this on your own. This one's a bit tricky because there is some syntax I haven't shown you yet, but maybe you'll figure it out, especially with the hint I gave you. Again, function call, think of that. How did that go for you? Were you able to figure it out with the hint I gave you? That one was a bit tricky. So, if you got it, that's amazing. Regardless, let's do it together so you can see how I'd implement it. So, to the header file first. We'll go here, and we need three parameters: numWindows and stringColor. Alright, so we can have an overload. Constructors have overloads just like any function. Only the destructor can't, but constructors can. And then over here, before the destructor, the order doesn't really matter, but to stay organized, I'm going to keep it the same order. Now, we also have to have one, we have to have the name of the class and the scope resolution operator. Perfect. This numStories is = numStories, which is the parameter, this numWindows is = numWindows, and this color = color. And then, we have to also test the House constructor that we just created. So, I'm going to make a house called House theirHouse and maybe you figured it out from the hint I gave you that it looks like a function call. Open, there you go. So, you got 2, 10 and green we'll say. So, the number of stories is 2, number of windows is 10, and then the color of the house is green. And somewhere along the line, we probably should do a print. So, at the very end I'll put theirHouse.print. So, we should get some sort of information about our new little house here. All right, so, the last print out we get before the destructors, right? Three destructors, the last print out we get, print call was, the house is green, it has 2 stories and 10 windows. Awesome. Good job everyone. I hope you all feel that you are learning a tremendous amount. Just remember that for some of you, you might go through the material once and learn it very well, or maybe you're even already somewhat familiar with it from taking a course or reading a book or something else and that's great. And then for others of you, you might struggle more. Maybe you don't understand all the nuances or you sometimes just shake your head and feel discouraged like you're not going to learn everything. Maybe you have to go through the lectures or even entire sections more than once to understand them better. That's totally fine. If software engineering and programming were easy, everyone would do it. You're acquiring a skill that relatively speaking, not many people have, don't get discouraged. There's an English idiom or saying that we use, Rome wasn't built in a day. It means obviously that big, complex tasks take time sometimes and you must realize that and put your best foot forward. Do as well as you can. Software is a massive industry and almost every other industry uses software and software developers. So, keep your eye on the prize. You want to have an in demand skill set, programming and problem solving are a major part of that skill set. I'd be willing to bet if you feel like you're struggling now, if you went back to the projects or some of the earlier lectures, say near the beginning of the course and revisited them, you'd think, wow, I used to think this stuff was hard, but now it's easy. That is probably the case for many of you. Moving forward, in the next lecture, we will practice some of our newfound skills by building a class together. This class will represent a rectangle, which could very well be useful in a geometry library or graphics library or maybe a game engine. So, let's get going.

 

About the Author
Students
297
Courses
20
Learning Paths
4

John has a Ph.D. in Computer Science and is a professional software engineer and consultant, as well as a computer science university professor and department chair.

Covered Topics