Easy tutorial for C / C ++ - class 3 (Constructor)
Constructor :
- Initialization of an object usually means initialization
of member variables. Commonly member variables are set to 'private', you need
to change the access specifier to 'public' or define the initialization
function separately to initialize it arbitrarily.
- A special function provided to compensate for this is
the Constructor. A constructor is a special member function for initializing an
object. It has the same name as the class name and does not specify the data
type of the return value. You can also overload with different arguments.
- If the programmer does not define a constructor, the C
++ compiler automatically creates a default constructor. It is equivalent to a
class name, and has no role as an argumentless constructor.
- Let's look at an example.
Example Code
#include
<iostream>
#include
<iomanip>
using
namespace std;
class
tClass{
private :
int Na;
int Nb;
public :
tClass();
tClass(int, int);
void prn();
};
tClass::tClass(){
Na = 10;
Nb = 20;
}
tClass::tClass(int
A, int B){
Na = A;
Nb = B;
}
void
tClass::prn(){
cout << " Na = " <<
Na << ", Nb = " << Nb << endl ;
}
int
main() {
tClass x;
cout << " Class x "
<< endl ;
x.prn();
cout << endl ;
tClass y(50,60);
cout << " Class y " <<
endl ;
y.prn();
return 0;
}
- We created the class 'tClass' and declared the member
variables 'Na, Nb'. We created a constructor 'tClass ()' with no arguments and
a constructor 'tClass (int, int)' with two integer arguments.
- Constructor 'tClass ()' is a constructor that
initializes the member variables Na and Nb to 10 and 20, respectively. The
constructor 'tClass (int, int)' allows the user to set the initial values of
the member variables Na and Nb when creating the object.
- First we declare the object 'x' in the main function
and print the value of the member variables. Let 's declare object' y 'and give
parentheses' ()' to input values 50 and 60. In this case, a constructor with
two integer arguments is called and the given value is assigned to each member
variable. Let's call the function 'prn ()' to check the result.
results
:
Class x
Na = 10, Nb = 20
Class y
Na = 50, Nb = 60
- For object 'x', a constructor with no arguments is
called and the result is 10 and 20 for Na and Nb, respectively. If you call the
output function 'prn ()', you will see that 10 and 20 are output.
- When
declaring object 'y', we gave two arguments 50 and 60. At that time, a
constructor with two arguments is called, and 50 and 60 are assigned to each
member variable. When you call the output function 'prn ()', you will see that
50 and 60 are output.
No comments:
Post a Comment