Unit 2 C
Unit 2 C
Unit-2
1. Default Constructor
Example:
In this example, Simple has a default constructor that initializes number to 0. When
you create an object obj of Simple, it automatically calls this constructor.
2. Parameterized Constructor
Example:
Here, Simple has a parameterized constructor that sets number to the value provided
(in this case, 42).
3. Copy Constructor
A copy constructor creates a new object as a copy of an existing object. It’s used
when you need to duplicate an object.
Example:
In this example, obj2 is created as a copy of obj1, using the copy constructor.
Overloading
Overloading in programming refers to the ability to use the same name for different
functions, operators, or constructors within a class, where the specific behavior is
determined by the context in which they are used. This concept is especially prevalent
in object-oriented languages like C++ and Java.
Function Overloading
Function overloading lets you create multiple functions with the same name, but with
different parameter lists.
Example
Explanation
Stream:
cin: Input stream, usually associated with the keyboard (for user
input).
cout: Output stream, usually associated with the screen (for
displaying output).
cerr: Output stream for errors.
Here’s an example to illustrate how cin and cout work in a simple C++
program:
Explanation:
1. std::cin >> name; reads the input from the console and stores
it in the variable name.
3. The final std::cout displays the entered data, using the values stored
in name and age.
Key Points: