Programming tutorials - page 3

 

OOP Constructors - Types of Constructors You Need to Know (Basics to Mastery)



OOP Constructors - Types of Constructors You Need to Know (Basics to Mastery)

In this video, we'll be discussing different types of Constructors, their purpose, and why they are essential in programming. I'll provide examples and explain the background workings of Constructors. But before we dive in, I want to recommend a tool I've been using for years called PBS Studio. It's a powerful static code analyzer that helps track down bugs and improve code quality. It integrates easily with various IDEs and supports languages like C, C++, C#, and Java. You can find the download link and even discover ways to get it for free if you're a student. Now, let's return to the video.

To start, let's create a class called "User" with public members: "firstName," "lastName," "age," and "email." Currently, we manually assign values to these properties for each user we create. However, this approach becomes impractical as the number of users grows.

Instead, we'll explore a better solution using Constructors. Constructors are used to construct objects, and they automate the process of initializing object properties. We'll begin by explaining the background workings of Constructors through examples.

For demonstration purposes, let's remove the second user and print the information of the first user. By running the program, you'll notice that the output displays empty values for firstName, lastName, and email, and a large or small number for age. We'll explore why this happens and the absence of any errors.

The reason behind this behavior is the default Constructor provided by C++. It initializes properties with default values, such as the large number we see for age. However, when we create a simple variable, like "test," without initializing it, we encounter an error because simple types don't have default Constructors.

Now, let's examine the characteristics of Constructors. First, Constructors have the same name as the class and no return type. Second, they need to be placed in the public section of the class. Third, default Constructors have no parameters. Fourth, C++ automatically generates a default Constructor if you don't create one. Fifth, parametrized Constructors receive parameters to initialize object properties. Finally, a default Constructor is invoked automatically when an object of that class is created.

Let's implement our own default Constructor by assigning default values to the properties. With this change, every time we create a user, our default Constructor will be invoked. Now, when we print the user information, we'll see the default values we assigned.

Moving on, let's explore the second type of Constructor, the parametrized Constructor. Unlike the default Constructor, the parametrized Constructor accepts specific values as parameters and uses them to instantiate object properties. I'll provide an example of a parametrized Constructor that takes parameters for firstName, lastName, and age.

With these parameters, we can assign the provided values to the corresponding properties. This allows us to create users with specific information directly during object creation.

That covers the basics of Constructors and their usage. Stay tuned for more examples and insights in future videos.

OOP Constructors - Types of Constructors You Need to Know (Basics to Mastery)
OOP Constructors - Types of Constructors You Need to Know (Basics to Mastery)
  • 2023.03.21
  • www.youtube.com
📚 Learn how to solve problems and build projects with these Free E-Books ⬇️C++ Lambdas e-book - free download here: https://bit.ly/freeCppE-BookEntire Objec...
 

Friend functions and classes in C++ (Programming for beginners)



Friend functions and classes in C++ (Programming for beginners)

In this video, I'm excited to teach you about friend functions and friend classes in C++. This concept of friendship in programming is similar to friendship in real life. Just like your friends have access to private areas of your life that others don't, friend functions and friend classes in object-oriented programming have access to private and protected members of a class.

In this video, you will learn how and when to use friend functions and friend classes. To demonstrate, we will use Visual Studio Community, and I'll also introduce you to an excellent extension called Visual Assist. You can find the download link in the description below. Visual Assist is a smart coding assistant that many professional developers use, especially for large projects or game development with engines like Unreal Engine. It enhances code completion, offers smart suggestions for refactoring, provides code snippets, and improves navigation and searching within your project.

Now, let's dive into the topic of friend functions. To explain this concept, let's create a problem and solve it using friend functions. We'll create a class called "EquilateralTriangle" to represent a triangle with all three sides of the same length. The class will have private variables for the side length, circumference, and area. We'll also add a public setter method to set the side length and calculate the circumference and area within that method.

However, if we try to access the private members outside the class, we'll encounter errors. One solution is to make the private members public or create public getters, but that exposes them to everyone. Instead, we can use friend functions to selectively grant access. We'll create a global function called "PrintResults" that will print the circumference and area of the triangle. By declaring this function as a friend of the EquilateralTriangle class, it gains access to the private members.

But remember, choose your friend functions carefully and avoid excessive use to maintain encapsulation. Additionally, in C++, you can also have friend classes. If we move the "PrintResults" function inside a class called "Homework" and make it a public member function, we can declare "Homework" as a friend class of "EquilateralTriangle". This way, "Homework" class can access the private and protected members of "EquilateralTriangle".

It's important to note that friendship in programming is not mutual or inherited. Use friend functions and friend classes judiciously, and remember that inheritance and operator overloading also involve common use cases for friend functions. Check out my video on operator overloading (linked in the description) for more information and a related homework exercise.

I hope you find this video helpful in understanding and utilizing friend functions and friend classes in your programming projects. Stay tuned for more exciting content, and don't forget to check out the Visual Assist extension for Visual Studio!

Friend functions and classes in C++ (Programming for beginners)
Friend functions and classes in C++ (Programming for beginners)
  • 2021.12.21
  • www.youtube.com
📚 Learn how to solve problems and build projects with these Free E-Books ⬇️C++ Lambdas e-book - free download here: https://bit.ly/freeCppE-BookEntire Objec...
 

Destructors in Programming: Practical Demonstration



Destructors in Programming: Practical Demonstration

In this video, I'll teach you about destructors in programming. You'll learn what destructors are, how to use them, and when to use them. Make sure to watch the entire video because I have a special surprise for you at the end. Before we dive into destructors, it's important to understand constructors. If you're not familiar with constructors, watch my previous video linked here and in the description.

Destructors are special functions invoked when an object is being destroyed. They perform necessary cleanup tasks, such as releasing resources like memory or files held by the object. Failing to release these resources can degrade performance, stability, and lead to memory leaks.

Before we start discussing destructors, I want to introduce you to a tool I love to use called PBS Studio. It's a static code analyzer that helps me write better code without bugs. It analyzes your code for potential issues and bugs, saving you time and money by catching errors before they go into production. It's easy to integrate with popular IDEs and supports multiple programming languages. You can download it from the link in the description and try it for free. If you're a student, check their website for free options.

Now, let's delve into destructors. A destructor is a special function with a name identical to the class name, preceded by a tilde (~). It doesn't have a return type, doesn't receive any parameters, and should be placed in the public section of your class. There can only be one destructor per class.

To illustrate destructors, let's create a class called "Book" with two properties: "title" and "author." We'll also create a constructor and a destructor. Remember, the destructor should deallocate any resources held by the object.

Inside the constructor, we'll assign the passed parameters to the corresponding properties. Inside the destructor, we'll output a message indicating that the destructor was invoked for a specific book.

Now, let's create some book objects to see when the constructor and destructor are invoked. We'll debug the program and observe the order of invocation.

If your class doesn't involve pointers, the compiler will handle memory deallocation automatically. However, if you're working with pointers, you need to manually deallocate memory in the destructor to avoid memory leaks. Remember to use "delete[] arrayName" for arrays and set pointers to nullptr after deallocation.

I hope this video helped you understand destructors and their importance in managing resources. In my next video, we'll explore copy constructors, so stay tuned.

Destructors in Programming: Practical Demonstration
Destructors in Programming: Practical Demonstration
  • 2023.03.29
  • www.youtube.com
📚 Learn how to solve problems and build projects with these Free E-Books ⬇️C++ Lambdas e-book - free download here: https://bit.ly/freeCppE-BookEntire Objec...
 

C++ Copy constructors (beginner-friendly tutorial + practical examples)



C++ Copy constructors (beginner-friendly tutorial + practical examples)

Hi everyone, welcome to my channel. In this video, I'll teach you about copy constructors, which is an important but confusing topic for beginners. Before watching this video, please make sure to watch my previous video on different types of constructors, including default and parametrized constructors (link in the description). Also, check out my video on pointers and dynamic arrays (link in the description) as it will help you understand this topic better.

In this video, I'll explain everything you need to know about copy constructors. Beginners often understand the concept behind copy constructors, but struggle with understanding when and how to use them, as well as the potential bugs and errors that can occur. I'll cover all of these aspects step by step.

Let's start by examining the code from my previous video. I've created a class called "Book" with properties such as title, author, and a pointer called "rates." The "rates" pointer represents a dynamic array where users can input ratings for the book. There's also a "rates counter" to keep track of the array size. If you're not familiar with pointers and dynamic arrays, I recommend watching my video on this topic (link in the description).

I've implemented a parametrized constructor for the Book class, which takes title and author as parameters and creates a book object based on those values. I've also included a destructor, which is important for releasing memory allocated by the constructor. It's crucial to use a code analyzer like PVS-Studio to detect hidden errors and weaknesses in your code. I personally recommend using PVS-Studio as it's effective in finding errors and providing suggestions for fixing them. You can download it for free using the link in the description.

Now, let's focus on the topic of copy constructors. The purpose of a copy constructor is to create a new object based on an existing object. It allows you to make a copy of an object and use it to create a new one. By default, C++ provides a default copy constructor. However, when working with pointers, it's necessary to create a custom copy constructor to avoid errors.

Without a custom copy constructor, using pointers can lead to exceptions and errors. Let's consider the following scenario: I want to create "Book3" based on the data of "Book1." I want to copy all the properties of "Book1" to create "Book3." This is where the copy constructor comes into play.

To create a copy constructor, follow these rules:

  1. It should be declared in the public section of the class.
  2. It doesn't have a return type (not even void).
  3. Its name should match the class name.
  4. It takes a parameter of the same class type, which represents the original object.

Let's create the copy constructor. In the copy constructor, we'll receive the original object as a constant reference (const Book& original). This prevents any modifications to the original object inside the copy constructor.

Now, let's address a common mistake made by beginners when creating a copy constructor. The mistake lies in copying the pointer directly instead of allocating new memory and copying the content. If we copy the pointer, both the original and the copy will point to the same memory location. As a result, when the destructor is invoked, it will attempt to release the memory twice, leading to errors.

To fix this issue, we need to allocate new memory for the copy and copy the content of the original pointer. Instead of directly assigning the pointer, we'll create a new dynamic array and copy the elements. This ensures that the original and copy have separate memory locations.

By following these guidelines, we can create a correct copy constructor that avoids memory-related errors.

I hope this explanation clarifies the concept of copy constructors and their importance.

C++ Copy constructors (beginner-friendly tutorial + practical examples)
C++ Copy constructors (beginner-friendly tutorial + practical examples)
  • 2023.04.19
  • www.youtube.com
This is an OOP tutorial where I'll teach you about copy constructors in C++. After watching this video, you'll learn what is the purpose of copy constructors...
 

Code-It-Yourself! Tetris - Programming from Scratch (Quick and Simple C++)



Code-It-Yourself! Tetris - Programming from Scratch (Quick and Simple C++)

Hello! Today, we're going to embark on the exciting journey of creating our own version of Tetris. Before we delve into coding, let me give you a sneak peek of what we'll be building.

As you can see, we have a classic Tetris shape on the screen. We'll be able to rotate these shapes, thanks to the power of coding. The game includes collision detection, which ensures that the pieces interact correctly with each other. If we manage to complete a line by strategically placing the random pieces, it will disappear, and our score will increase accordingly. However, if we're not careful and the stack of pieces reaches the top, it's game over.

Now, you might be wondering why we're focusing on the game engine rather than the graphics. While aesthetics are important and can attract players, the real essence of a game lies in its engine—the part responsible for implementing gameplay, logic, rules, challenges, and more. Graphics engines can always be added later, and you can even bring in an artist to beautify your game. But to truly understand game development, you need to grasp the fundamentals of building a game engine.

To get started, we need some game assets. In Tetris, these assets are the different shapes called "tetromino blocks." We'll store these shapes as strings, which will make it easier for us to visualize them. There are seven common shapes used in Tetris, and we'll represent them using characters such as periods (.) for empty spaces and capital X for the shape itself. By arranging these characters, we create strings that visually depict the shapes.

Now, instead of using multi-dimensional arrays to represent the 2D shapes, we'll employ a single-dimensional array and manipulate the indices using simple mathematical calculations. This approach allows us to handle rotations and reflections of the shapes more efficiently. We'll use formulas to determine the appropriate indexes for each rotation. For example, by multiplying the X coordinate by 4, we can obtain the desired index for a 90-degree rotation. This technique will save us from creating separate assets for every possible shape variation.

Apart from the tetromino blocks, we also need a playing field. We'll define the dimensions of the field using variables for width and height. In this case, we'll go with a field size of 12 cells wide and 18 cells high. To represent the elements of the playing field, we'll use an array of unsigned characters. Each cell will be assigned a value to indicate its contents, such as empty space, part of a shape, or the boundary walls.

To visualize our game, we'll utilize the command prompt as a screen buffer. By creating an array with the dimensions of the command prompt window, we can draw our game elements on it. We'll use specific characters to represent different elements of the game, like the shapes, empty spaces, and the boundary walls. Then, we'll display the contents of the array on the command prompt screen.

Now, let's talk about the game loop. Game loops are vital components of any game engine as they control the sequencing of the game's elements. In the case of Tetris, our game loop will handle timing, user input, game logic, and output rendering.

Timing is crucial to ensure consistent gameplay across different systems. We want the game to run at the same pace, regardless of the computer's speed. We'll use timing mechanisms to control the speed at which the shapes fall and the game updates.

Next, we'll address user input. Since we're creating a simple command-line version of Tetris, we won't rely on event-based input. Instead, we'll handle basic user input, such as arrow keys or other designated keys.

In this code, we will be implementing keyboard input handling for a game, specifically focusing on four keys: the left arrow, right arrow, down arrow, and the "Z" key for rotating the game piece.

To obtain the current state of the keys pressed by the user, we will utilize the "get async key state" function. By iterating through an array representing the state of the keys, we can determine if each key is currently pressed or not. This function returns a boolean value: true if the key is pressed and false if it is not. To check the state of a specific key, we use a constant string expression representing the virtual key codes for each key.

By checking the state of these four keys, we can create an array that holds true or false values indicating whether each key is pressed or not. This simplifies the process and gives us an array representing the current state of the keys.

Let's consider the left key as an example. When the user presses the left key, we need to check if the game piece can fit to the left of its current position. To do this, we utilize a function called "does piece fit," which considers the current piece, its rotation, and the current X position. By subtracting 1 from the current X position, we can determine if the piece fits to the left. If it does fit, we update the current X position accordingly.

Similarly, for the right key, we perform a similar check to see if the piece can fit to the right of its current position. If it can, we update the current X position accordingly.

When the user presses the down key, we need to handle the vertical motion of the piece. As the top-left position of the playing field is always (0, 0), we can simply increment the Y position to move the piece down. We perform checks to ensure that moving the piece left, right, or down keeps it within the boundaries of the playing field.

To optimize the code, we can replace the nested if statements with logical AND operators. This simplifies the code and improves its conciseness. Additionally, we utilize conditional statements to add or subtract 1 from the current X position based on the condition's result, further streamlining the code. The same optimization is applied when handling the rotation of the piece when the user presses the "Z" key.

In Tetris, the game periodically forces the piece to move down every few tenths of a second, simulating gravity. We achieve this by utilizing the game tick counter. Initially, the piece falls slowly, but as the game progresses, we decrease the time between each piece fall, making the game faster and more challenging. By accumulating game ticks and comparing them to the current speed, we determine when to force the piece down. This results in the piece falling at regular intervals, creating the effect of gravity in the game.

To lock the current piece into the playing field, we update the field array with the values from the tetromino array. This is done by iterating through each element of the tetromino array and updating the corresponding position in the field array. If an element in the tetromino array is an "X," we increment the corresponding value in the field array by 1. This marks that position as occupied by the current piece.

When a line is formed in the playing field, we want to visually indicate it to the player. We replace the line with a special marker or perform any other visual effect to indicate the completion of the line.

After visually indicating the completed line, we need to handle clearing the line and updating the playing field accordingly. We iterate through each row of the playing field starting from the bottom and check if the row is filled. If a row is filled, we clear it by setting all its elements to 0. We then move all the rows above it down by one position to fill the cleared row. This process is repeated until all filled rows have been cleared.

To keep track of the player's score, we increment it every time a line is cleared. The score can be based on the number of lines cleared or can have a more complex scoring system depending on the game's design.

To handle game over conditions, we need to check if the current piece can fit in its initial position at the top of the playing field. If it cannot fit, the game is over, and we stop the game loop or trigger any necessary game over actions.

Lastly, to handle the game loop, we utilize a timer or a similar mechanism that triggers an update function at a regular interval. This function handles updating the game state, including checking for user input, moving the piece down, and performing necessary actions based on the current game state.

In summary, this code implements keyboard input handling for a game, specifically focusing on keys such as arrow keys and the "Z" key. It checks the state of these keys, handles the movement of the game piece accordingly, implements gravity and piece locking, clears completed lines, updates the playing field, tracks the player's score, and checks for game over conditions. The game loop ensures that the game state is updated at regular intervals, creating a dynamic and interactive gameplay experience.

Code-It-Yourself! Tetris - Programming from Scratch (Quick and Simple C++)
Code-It-Yourself! Tetris - Programming from Scratch (Quick and Simple C++)
  • 2017.04.03
  • www.youtube.com
I mentioned in an earlier video that programming a Tetris clone is a good way to get going with programming as it makes you think about algorithms. Putting m...
 

C++ FULL COURSE For Beginners (Learn C++ in 10 hours)


C++ FULL COURSE For Beginners (Learn C++ in 10 hours)

This is a full C++ programming course. It consists of many lectures whose goal is to take you from beginner to advanced programming level. I recommend watching the entire video because later lectures require knowledge from previous ones.

Contents:
00:00:00
– Goals of the course
00:01:31 – Do this before starting the course
00:02:41
– Introduction to C++ (What is C++? What kind of apps can you build with C++? Why C++ was created?)
00:06:39 – What is source code, object code, compiler, algorithm?
00:08:42
- Visual Studio 2019 – Creating a first project (setup)
00:11:32 - Visual Studio 2019 basics explained and first “Hello World” program
00:29:51
- Introduction to variables
00:44:36 – Rules for naming variables
00:52:15
– Data types in C++ and how to use sizeof operator
01:01:58
- Data type overflow
01:05:00 – What is ASCII table
01:09:50
- Simple, fun program for ciphering words into ASCII
01:18:12 - If/else statement (Build a program that checks odd/even numbers + flowchart explanation)
01:35:52 - Nested if/else statement (Build a program that determines the type of a triangle + flowchart)
01:55:50 - Operators in C++ (arithmetic, relational, logical, assignment operators)
02:21:02 - Swapping values of two variables with or without a third variable
02:29:20– Build BMI Calculator application + flowchart
02:49:55 - Ternary (Conditional) operator (Build a Guessing game app)
03:01:00 - Switch/case statement part 1 (Build Calculator app)
03:26:36 - Switch/case statement part 2 (Build program that checks number of days in a month)
03:39:35
- While loop part 1 + infinite loop example
03:53:39 - While loop part 2 (Build a program for counting digits of a number)
04:12:39
- While loop part 3 (Build a program for reversing digits of a number)
04:25:25
- Do while loop (Program for PIN validation)
04:39:09 – What is the difference between While loop and Do While loop
04:40:34 - For loop (Build a program for calculating the factorial of a number)
04:58:12 – Nested loops (Nesting do while loop and for loop)
05:11:08 – Nested for loop (Build Multiplication table app)
05:21:45 – Program for drawing rectangle shape
05:33:05 – Program for drawing triangle and inverted/reversed triangle shapes
05:44:30 – Introduction to functions
05:56:02 – Functions with parameters/arguments (multiple and default)
06:11:42
- Function return statement (Build program for checking prime numbers)
06:37:39
- Function overloading
06:48:06 – Build ATM app
07:03:03 - Generic functions and templates
07:14:30 – Recursion and recursive functions
07:30:01
– Introduction to OOP, What are classes and objects
07:42:06
– OOP Constructors and class methods
07:57:10 – OOP Encapsulation, GIT: https://github.com/TrueCodeBeauty/EncapsulationCpp
08:08:31 – OOP Inheritance, GIT: https://github.com/TrueCodeBeauty/InheritanceCpp
08:24:59 – OOP Polymorphisam, GIT: https://github.com/TrueCodeBeauty/PolymorphismCpp
08:40:04 - Introduction to pointers
08:51:14 - Void pointers
09:06:27 - Pointers and arrays
09:19:18
- Return multiple values from a function using pointers
09:34:50
- Dynamic arrays, create/change arrays at runtime
09:48:35 – Multidimensional dynamic arrays, Two-dimensional array
10:07:00
- Detecting errors in code using PVS Studio
10:17:19 - Explaining Memory Leaks
10:26:25 - Bloopers
C++ FULL COURSE For Beginners (Learn C++ in 10 hours)
C++ FULL COURSE For Beginners (Learn C++ in 10 hours)
  • 2021.01.11
  • www.youtube.com
This is a full C++ programming course. It consists of many lectures whose goal is to take you from beginner to advanced programming level.I recommend watchin...
 

C++ FUNCTIONS (2020) - What are functions?


C++ FUNCTIONS (2020) - What are functions? PROGRAMMING TUTORIAL

Welcome to the first video of my channel! If you're a beginner at C++, make sure to check out my playlist on C++ for beginners, where you can find important concepts you need to understand and know to work with C++. In this video, we will discuss C++ functions, which are essential for becoming a good programmer not only in C++ but in most programming languages.

Before we begin, please subscribe to my channel and click the bell icon to receive notifications when I publish my next video. If you're interested in seeing behind-the-scenes content and how the developer life really looks, follow me on Instagram and Twitter through my accounts "CodeBeauty".

Now, let's dive into the topic of functions. A function is a block of code that is grouped together to solve a specific problem or perform a specific task. The code within a function is executed only when the function is called or invoked. Every C++ program contains at least one function, which is the main function. The execution of your program starts at the first line of the main function and ends either at the last line or when a return statement is encountered (we will cover return statements later in this course).

To create your own function, there are a few things you need to know. First, you need to specify the return type of the function. For now, we'll use the "void" return type, which means the function doesn't return anything. Next, you give a name to your function. Inside the parentheses, you can define any arguments or parameters that your function receives. In this case, we won't have any arguments, so the parentheses are empty. Finally, you define the body of the function within curly brackets.

In our example, we've created a function called "function" with a void return type and no arguments. Inside the function's body, we use the "cout" statement to display "Hello from function" and add an endline. However, simply creating the function doesn't execute its code. To execute the function, you need to invoke or call it. In our case, we call the function after the "cout" statement in the main function by typing its name followed by parentheses.

After compiling and running the program, you will see the output "Hello from main" followed by "Hello from function." This is because the main function is executed first, and then the function we created is executed when it is invoked.

To make your code more readable, it is recommended to declare and define your functions separately. The declaration includes the return type, function name, and any parameters, and it should be placed before the main function. The definition, which contains the function's body, is placed after the main function. This way, if someone else is reading your code, they can easily navigate to the specific function they need to understand.

Remember that functions make your code reusable. Instead of writing the same code multiple times, you can write it once inside a function and invoke that function whenever you need it. This practice helps to reduce redundancy and makes your code easier to manage.

In future videos, we will explore functions in more detail. Don't forget to subscribe to my channel and enable notifications to stay updated with the upcoming content. Thank you for watching, and I'll see you in the next video!

C++ FUNCTIONS (2020) - What are functions? PROGRAMMING TUTORIAL
C++ FUNCTIONS (2020) - What are functions? PROGRAMMING TUTORIAL
  • 2020.06.11
  • www.youtube.com
This is the introduction video of the "C++ functions" course. In this video, I'm explaining what are C++ functions, how functions are created, when they're u...
 

C++ FUNCTIONS (2020) - What is function parameter/argument (multiple, default) PROGRAMMING TUTORIAL


C++ FUNCTIONS (2020) - What is function parameter/argument (multiple, default) PROGRAMMING TUTORIAL

Hello, everyone! Welcome back to my channel. If you're a beginner to C++, I'm glad you're here. Before we dive into today's topic, I want to remind you to check out my C++ for beginners playlist. It covers essential concepts and includes plenty of exercises to help you practice. Also, don't forget to subscribe to my channel and click the bell icon to receive notifications whenever I release a new video. You can also follow me on my social media profiles, CodeBeauty Instagram and Twitter, to get a sneak peek into a developer's life. Alright, without further ado, let's jump into today's lesson.

In this video, I want to discuss C++ function parameters or arguments. So, what exactly are parameters and arguments? If you haven't watched my previous video on C++ functions, I recommend checking it out (link provided). Sometimes, a function needs to receive a specific value or variable in order to perform a particular task. These values or variables are called parameters.

Now, let's learn how to create a function that accepts parameters in C++. To do this, we define a function with a return type of void. Let's name the function "introduceMe." Inside the parentheses, we specify the parameters the function will receive. The body of our function will be enclosed in curly brackets.

To define a parameter, we start by stating the type of the parameter, followed by its name. In our case, we want to pass the name of our user to the function, so the parameter will be of type string. We'll name the parameter "name." The function will then introduce our user by printing "My name is" followed by the provided name.

To invoke or call our function, we simply use its name, "introduceMe." Since our function requires an argument (the name parameter), we need to pass a value when calling the function. In this case, let's pass the name "Selena" as the argument.

When we run the program, the function will successfully introduce the user with the provided name. It will print "My name is Selena" as expected.

If we want to introduce multiple users, we can call the function again with different arguments. For example, we can copy the invocation line and pass a different name, such as "Anna." The function will then introduce both users accordingly.

Now, let's explore passing multiple arguments to a function. To do this, we separate the parameters with commas. In addition to the name parameter, let's add two more parameters: city (of type string) and age (of type int). We'll modify the function to include information about the user's city and age as well.

Within the function, we'll use C++'s "cout" to print out the user's city and age along with their name. We'll structure the output as follows: "I am from [city], and I am [age] years old."

When we invoke the function, we pass the values for all three parameters: name, city, and age. For example, we can call the function and pass "Selena" as the name, "Moscow" as the city, and 25 as the age. The function will introduce the user with all the provided information.

We can repeat the process for a second user. Let's pass "Anna" as the name, "New York" as the city, and 27 as the age. When we run the program, we'll see that both users have been introduced with their respective details.

Next, let's explore default parameters. Sometimes, you may want to define a default value for a parameter. This value will be used if no argument is provided for that parameter when calling the function.

To specify a default value, we assign it during parameter declaration. For example, let's set the default value for the "age" parameter to 18. Now, if we call the function without providing an age, it will assume the default value.

Let's invoke the function for a third user, passing only the name and city, but omitting the age. As expected, the function will introduce the user with the default age value of 18.

That wraps up our discussion on C++ function parameters and arguments. I hope you found this video helpful and that you have a solid understanding of how to work with function parameters in C++. If you have any questions or need further clarification, please leave a comment below, and I'll be happy to assist you. Stay tuned for more C++ tutorials, and don't forget to like and share this video if you found it valuable. Thanks for watching, and happy coding!

C++ FUNCTIONS (2020) - What is function parameter/argument (multiple, default) PROGRAMMING TUTORIAL
C++ FUNCTIONS (2020) - What is function parameter/argument (multiple, default) PROGRAMMING TUTORIAL
  • 2020.06.15
  • www.youtube.com
In this video of the "C++ functions" course, I'm explaining what are function parameters/arguments, how to pass arguments to a function, and how to invoke a ...
 

C++ FUNCTIONS (2020) - Functions return statement, How to check prime number


C++ FUNCTIONS (2020) - Functions return statement, How to check prime number PROGRAMMING TUTORIAL

Hi everyone, welcome to my channel. In this video, I want to discuss return statements and return types of functions in C++. If you're a beginner, make sure to check out my C++ for beginners course, which provides useful examples to help you get started with learning C++. Don't forget to subscribe to my channel and click the notification bell to stay updated on new videos. Additionally, if you're interested in becoming a developer and gaining insights into the developer's life, follow me on Instagram and Twitter at @truecodebeauty (links in the video description). Without further ado, let's dive into today's topic.

A return type of a function can be any data type, including int, float, bool, char, double, or even user-defined data types. It can also be void, indicating that the function doesn't return anything. In previous videos, I explained that a function is a block of code designed to perform a specific task. Functions can be categorized into two types: those that return a value and those that don't.

Functions that don't return a value typically perform a specific action, such as displaying a menu to the user. On the other hand, functions that return a value are used to perform calculations or operations and provide a result. It's important to note that a function can only return one value, and once the return statement is encountered, the function execution stops.

To illustrate the importance of functions, let's consider an example without using functions. We'll create a program to determine whether a number is prime or not. A prime number is divisible only by one and itself. First, we'll ask the user to enter a number. Then, we'll iterate through all numbers between 2 and the user-entered number minus 1. If the number is divisible by any of these values, it's not prime. Otherwise, it's prime. Finally, we'll display the result.

Now, let's refactor the program using functions to make the code more readable and reusable. We'll create a function called "isPrimeNumber" that takes an integer argument and returns a boolean value indicating whether the number is prime or not. Inside the function, we'll implement the same logic as before, checking for divisibility and setting a flag accordingly. Finally, we'll return the flag value.

By using functions, we can encapsulate the logic for determining prime numbers, making the code easier to understand and reuse.

C++ FUNCTIONS (2020) - Functions return statement, How to check prime number PROGRAMMING TUTORIAL
C++ FUNCTIONS (2020) - Functions return statement, How to check prime number PROGRAMMING TUTORIAL
  • 2020.06.29
  • www.youtube.com
In this video of the "C++ functions" course, I'm explaining what is the function return type. I'll show you how to return value from a function on an example...
 

C++ FUNCTIONS (2020) - What is function overloading? PROGRAMMING TUTORIAL


C++ FUNCTIONS (2020) - What is function overloading? PROGRAMMING TUTORIAL

Hello, everyone! Welcome back to my channel. In today's video, we're going to dive into the concept of function overloading in C++. Function overloading allows us to create multiple functions with the same name but different parameters. So, let's explore what function overloading is and how it works.

To begin, let's open our Visual Studio and create a function called "sum". We'll start by defining the return type of our function, which will be an integer. If you're unfamiliar with return types, I recommend watching my video on the topic (link provided). Next, we'll specify the name of our function as "sum" and declare two parameters. Both parameters will be of type integer, and we'll name them "a" and "b" respectively.

Now, let's create another function with the same name, "sum", but this time with a return type of double. We'll declare two parameters of type double, named "a" and "b".

Additionally, let's create a third function named "sum" with a return type of float. This time, we'll pass three parameters, all of which will be of type float. We'll name them "a", "b", and "c" respectively.

After declaring our functions, we notice that they are underlined, indicating that they are missing their definitions. Let's proceed by providing the definitions for each function. We'll start with the first function that returns an integer.

Inside the curly brackets, we'll define a variable called "result" of type int. We'll assign it the value of "a + b", which represents the sum of the two parameters. Finally, we'll use the "return" keyword to return the value of "result" from the function.

Alternatively, instead of creating a separate variable, we can directly return the sum of "a" and "b" without assigning it to a variable. This can make the code shorter and more readable.

Next, let's define the second function that returns a double. We'll copy the declaration, add the curly brackets, and inside, we'll use the "return" keyword followed by "a + b". Since the parameters are of type double, the sum will be performed using double precision.

Now, let's define the third function that returns a float. We'll copy the declaration, add the curly brackets, and inside, we'll use the "return" keyword followed by "a + b + c". Again, since all parameters are of type float, the sum will be performed accordingly.

To test our functions, we'll invoke them in the "main" function. We'll use the "cout" statement to display the results. Let's start by calling the first function, "sum", and passing two integer values, such as 4 and 3. We'll output the result using "cout" and end the line.

When we run the program, we can expect to see the result of summing 4 and 3, which should be 7. If the program runs successfully, we have tested our first function.

Next, let's test the second function by calling "sum" and passing two double values, such as 4.4 and 3.3. Again, we'll output the result using "cout" and end the line.

When we run the program, we should see the result of summing 4.4 and 3.3, which should be 7.7. If the output is correct, we have successfully tested our second function.

Finally, let's test the third function by calling "sum" and passing three float values, such as 4.4, 3.3, and 2.2. We'll output the result using "cout" and end the line.

Running the program should display the result of summing 4.4, 3.3, and 2.2, which should be the correct sum. Verify the output using a calculator if needed.

In summary, what we've demonstrated here is function overloading. We created three functions with the same name, "sum," but with different parameters and return types. The first function takes two integers, the second takes two doubles, and the third takes three floats. When we invoke these functions, the compiler determines the appropriate function to call based on the arguments provided.

Function overloading allows us to write more concise and readable code by using the same name for functions that perform similar tasks. We don't need to create separate functions with different names for each variation.

I hope you now understand the concept of function overloading and how it can be useful in C++. If you enjoyed this video, please subscribe to my channel and click the bell icon to receive notifications for future videos. You can also follow me on my other social media platforms (links provided in the description).

Thank you for watching, and I'll see you in my next video. Bye!

C++ FUNCTIONS (2020) - What is function overloading? PROGRAMMING TUTORIAL
C++ FUNCTIONS (2020) - What is function overloading? PROGRAMMING TUTORIAL
  • 2020.07.17
  • www.youtube.com
Function overloading is the ability to create multiple functions that have the same name but different implementations. In this video of the C++ programming ...
Reason: